#!/usr/bin/perl -w

use strict;

my $Outfile;

# Process command line arguments
if ( $ARGV[0] =~ /^-o/i ) {
   if ( $ARGV[0] =~ /^-o$/i ) {
      $Outfile = $ARGV[1];
   } else {
      $ARGV[0] =~ /(?<=-o)(.*)/i;
      $Outfile = $1;
   }
}

unless ( $Outfile ) {
   die "Usage: $0 -o <output file>\n\n";
}

open( OUTFILE, ">$Outfile" ) or die "\nError: Couldn't open OUTPUT file $Outfile: $!";

print "Generating $Outfile...\n";

# Generate optimized functions
print OUTFILE "#define ISOPAQUE 0\n\n";

for ( my $Bitdepth = 16; $Bitdepth <= 32; $Bitdepth += 8 ) {
   print OUTFILE "// " . $Bitdepth . "-bit rendering functions.\n";
   print OUTFILE "#define BPP $Bitdepth\n\n";
   for ( my $Function = 0; $Function < 32; $Function++ ) {
      if ( ($Function & 15) == 0) {
         print OUTFILE "#define DOCLIP " . ($Function & 16) / 16 . "\n";
      }
      print OUTFILE "#define XZOOM " . ($Function & 15) . "\n";
      print OUTFILE "#include \"neo_sprite_render.h\"\n";
      print OUTFILE "#undef XZOOM\n";
      if ( ($Function & 15) == 15) {
         print OUTFILE "#undef DOCLIP\n";
      }
   }
   print OUTFILE "#undef BPP\n\n";
}
print OUTFILE "#undef ISOPAQUE\n\n";

# Create table with functions addresses
print OUTFILE "// Table with all function addresses.\n";
print OUTFILE "static RenderBankFunction RenderBankFunctionTable[] = {\n";
for ( my $Bitdepth = 16; $Bitdepth <= 32; $Bitdepth += 8 ) {
   my $FunctionName = "&RenderBank" . $Bitdepth;
   for ( my $Function = 0; $Function < 32; $Function++ ) {
      if ( ($Function & 15) == 0) {
         print OUTFILE "\t";
      }
      print OUTFILE "$FunctionName" . "_ZOOM" . ($Function & 15);
      if ( ($Function & 16) == 0 ) {
         print OUTFILE "_NOCLIP";
      } else {
         print OUTFILE "_CLIP";
      }
      print OUTFILE "_TRANS";
      print OUTFILE ", ";
      if ( ($Function & 15) == 15 ) {
         print OUTFILE "\n";
      }
   }
}
print OUTFILE "};\n\n";

print OUTFILE "static RenderBankFunction* RenderBankNormal[96] = {\n\t&RenderBankFunctionTable[0],\n\t&RenderBankFunctionTable[32],\n\t&RenderBankFunctionTable[64]\n};\n";

close( OUTFILE );

