# Define package name
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
package Bioware::TLK; #~~~~~~~~~~~~~~~
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

use strict;
require Exporter;
use vars qw ($VERSION @ISA @EXPORT);

use Win32::API;
my $msgbox=Win32::API->new('user32','MessageBoxA','NPPN','N');
# set version
$VERSION=0.04; #changed > to >= in if ($resrefnum>=$string_count)


@ISA    = qw(Exporter);

# export functions/variables
@EXPORT = qw( &string_from_resref );
#sub get_tlk4_string {
#    my $resrefnum=shift;
#    seek $tlkfh,12,0;
#    read $tlkfh,(my $string_count_packed),4;
#    my $string_count=unpack('V',$string_count_packed);
#    return '[Out of TLK file range]' if ($resrefnum>$string_count);
#    return '[Bad StringRef]' if ($resrefnum<=0);
#    seek $tlkfh,32+(10*$resrefnum)+4,0;
#    read $tlkfh,(my $info_packed),6;
#    my ($offset,$size)=unpack('Vv',$info_packed);
#    seek $tlkfh,$offset,0;
#    read $tlkfh,(my $string),$size;
#    return $string;
#
#}
sub string_from_resref($$;$) {
    my $tlk_path=shift;
    my $resrefnum=shift;
    my $breadcrumb=shift;
    (open TLK, "<", "$tlk_path\\dialog.tlk") || (return);
    
    seek TLK,0,0;
    read TLK,(my $tlkversion),8;

    seek TLK,12,0;
    read TLK,(my $string_count_packed),4;
    my $string_count=unpack('V',$string_count_packed);
    if ($resrefnum>=$string_count) {
      $msgbox->Call(0,"Attempted to read past end of end of dialog.tlk \n"
      ."(tried to read string $resrefnum but dialog.tlk only goes up to entry number " . ($string_count-1) .")"."\n\n$breadcrumb",
      "Dialog.tlk error",0);
      die "Dialog.tlk error: Attempted to read past end of end of dialog.tlk \n"
        ."(tried to read string $resrefnum but dialog.tlk only goes up to entry number " . ($string_count-1) .")"."\n$breadcrumb"
    }
    if ($tlkversion eq 'TLK V4.0') {
        seek TLK,32+(10*$resrefnum)+4,0;
        read TLK,(my $info_packed),6;
        my ($offset,$size)=unpack('Vv',$info_packed);
        seek TLK,$offset,0;
        read TLK,(my $string),$size;
        close TLK;
        return $string;
    }

    read TLK,(my $offset_packed),4;
    my $offset=unpack('V',$offset_packed);
    seek TLK, 20+(40*$resrefnum)+28,0;
    read TLK,(my $info_packed),8;
    my ($offset2,$size)=unpack('V2',$info_packed);
    seek TLK,$offset+$offset2,0;
    read TLK,(my $string),$size;
    close TLK;
    return $string;
}
1;
