use strict;
use warnings;

package HTMLParser;

# Forward declaration
sub spacePad($$);

# global data
my @objects;

# read file
sub parseFile($) {
    my $fname = shift;

    my @lines;
    open(my $fh, $fname) or die($!);
    @lines = <$fh>;
    close $fh;

    @objects = ();

    foreach my $line (@lines) {
        next if($line !~ /AREA\ SHAPE/o);

        $line =~ /ALT=\"(\d*)x(\d*)\_([^\"]*)/;
        my ($x, $y, $fname) = ($1, $2, $3);
        if(!$x) {
            #print "Can't handle line $line\n";
        } else {
            my %tmp = (
                       X => $x,
                       Y => $y,
                       FILE => $fname,
                      );
            push @objects, \%tmp;
            #print "$fname is at X: $x / Y: $y\n";
        }
    }
}

# Generate list (txt)
sub writeTXT($) {
    my $ofname = shift;
    open(my $ofhtxt, ">", $ofname) or die($!);
    foreach my $obj (@objects) {
        print $ofhtxt "X: " . spacePad($obj->{"X"}, 6) . "\t" .
                      "Y: " . spacePad($obj->{"Y"}, 6) . "\t" .
                      "FILE: " . $obj->{"FILE"} . "\n";
    }
    close($ofhtxt);
}

# Generate LUA init functions
sub writeBSL($) {
    my $ofname = shift;
    open(my $ofhbsl, ">", $ofname) or die($!);
    foreach my $obj (@objects) {
        print $ofhbsl "-- "  . $obj->{"FILE"} . " GFX\n";
        print $ofhbsl "gfx = LoadGFX(\"" . $obj->{"FILE"} . "\");\n";
        print $ofhbsl "-- "  . $obj->{"FILE"} . " OBJ\n";
        print $ofhbsl "obj = AddObject(gfx, " .
                            $obj->{"X"} . ", " .
                            $obj->{"Y"} . ", 0, 0, 0, 0);\n";
        print $ofhbsl "\n\n";
    }
    close($ofhbsl);
}



# Functions
sub spacePad($$) {
    my ($val, $len) = @_;
    while(length($val) < $len) {
        $val .= " ";
    }
    return $val;
}

1;
