#!/usr/bin/perl

# Convert mostly what other scripts don't : WRITE_HANDLER syntax (horrible),
# and GFX_LAYOUT mostly.

while (<>) {
  if (s/READ_HANDLER\((.+)\)/UINT8 $1\(UINT32 offset\)/ ||
      s/READ16_HANDLER\((.+)\)/UINT16 $1\(UINT32 offset\)/ ||
      s/WRITE_HANDLER\((.+)\)/void $1\(UINT32 offset, UINT8 data\)/ ||
      s/WRITE16_HANDLER\((.+)\)/void $1\(UINT32 offset, UINT16 data\)/) {
    chomp;
    my $line = <>;
    if ($line =~ /^\{/) {
      print "$_ {\n";
      while (<>) {
	print;
	last if ($_ =~ /^\}/);
      }
      print "\n";
    } else {
      print "$_\n";
      $_ = $line;
      redo;
    }
  }

  # copy the gfxlayouts blocks
  if (/GfxLayout.+\=/) {
    print;
    while (<>) {
      print;
      chomp;
      last if ($_ eq "};");
    }
    print "\n";
  }

  # convert gfxdecodeinfo stuff
  if (s/GfxDecodeInfo(.+\=)/GFX_LIST$1/) {
    print;
    while (<>) {
      my ($region, $start,$layout,$start_col,$banks) = split(/\, ?/);
      if ($banks) {
	$banks =~ s/ ?\}//;
	print "$region, $layout }, // $banks color banks\n";
	if ($start > 0) {
	  print STDERR "WARNING : GfxDecodeInfo has $region starting at $start\nYou will have to manually adjust this.\n";
	}
      } else {
	s/\-1/0\, NULL/;
	print;
      }
      chomp;
      last if ($_ eq "};");
    }
    print "\n";
  }
  if (/^GAME\( (.+) \)/) {
    my ($year,$name,$parent,$machine,$reste) = split(/\,/,$1);
    $name =~ s/ //g;
    $parent =~ s/ //g;
    $name = "_$name" if ($name =~ /^\d/); # stupid digit in front of the name
    $parent = "_$parent" if ($parent ne "0" && $parent =~ /^\d/); # stupid digit in front of the name
    print "static struct DIR_INFO $name\_dirs[] =\n";
    print "{\n";
    print "  { \"$name\" },\n";
    if ($parent ne "0") {
      print "  { ROMOF(\"$parent\") },\n  { CLONEOF(\"$parent\"), },\n";
    }
    print "  { NULL }\n";
    print "};\n\n";
  }
}
