#!/usr/bin/perl -w

# Red Dragon
$directory = '/home/upi/code/ms/Extractor/8810019.img';
$spritename = 'reddragon';
$spriteOffsetX = -86;
$spriteOffsetY = 38;
$spriteLogicalWidth = 96;
$spriteLogicalHeight = 64;

# Blue Dragon
# $directory = '/home/upi/code/ms/Extractor/.8810020.img';
# $spritename = 'bluedragon';
# $spriteOffsetX = -86;
# $spriteOffsetY = 38;
# $spriteLogicalWidth = 96;
# $spriteLogicalHeight = 64;

sub ReadFile {
  my ($fileName) = @_;
  my ($data);
  local $/ = undef;   # Read complete files

  if (open(IN, "<$fileName")) {
    $data=<IN>;
    close IN;
    return $data;
  }
  die "Can't open $fileName: $!";
}

sub ParseIndex {
  while ($index =~ /<img src='([^']+)'>/g) {
    push @images, $1;
  }
  print 'Images: ', join(',', @images), "\n";
  while ($index =~ /<td>([\w\.]+).origin.([xy])<\/td><td>([\d\-]+)/g) {
    $imageName = $1;
    $coordinate = $2;
    $position = $3;
    $imagePos{"$imageName.png"}->{$coordinate} = $position;
  }
}


$index = &ReadFile("$directory/index.html");
&ParseIndex();

open TRACE, "$directory/trace"  or die;
while (<TRACE>) {
  if (/^([\w\.]+) ([\d\-]+) ([\d\-]+) ([\d\-]+) ([\d\-]+)\s*$/) {
    $imageName = $1;
    $imagePos{$imageName}->{tx} = $2;
    $imagePos{$imageName}->{ty} = $3;
    $imagePos{$imageName}->{tw} = $4;
    $imagePos{$imageName}->{th} = $5;
#     print "Found texture $1 $2 $3 $4 $5\n";
  }
}

foreach $imageName (@images) {
  %imageData = %{$imagePos{$imageName}};
  next  unless $imageData{tw};
  
  ($sequenceName, $sequenceNumber) = $imageName =~ /^([\w\.]+)\.(\d+)\.png$/  or die "$imageName doesn't parse";
  $sequenceName =~ s/\./\_/g;
  $offsetX = $imageData{x} + $spriteOffsetX;
  $offsetY = - $imageData{y} + $imageData{th} + $spriteOffsetY;
  print "  \$Sprites{${spritename}_$sequenceName}->[$sequenceNumber] = new OffsetSprite('$spritename', $imageData{tx}, $imageData{ty}, $imageData{tw}, $imageData{th}, $spriteLogicalWidth, $spriteLogicalHeight, $offsetX, $offsetY);\n";
}
