if (! defined $ARGV[0] ) {
  print "Usage: perl $0 [FILENAME (without the .hex)]\n";
  print "Use Quartus MIF editor to save as HEX.\n";
  exit 1;
}

$file = $ARGV[0];

$in = $file . '.hex';
$out = $file . '.v';

if (! -e $in) {
  print "You file, $in does not exist!\n";
  print "Try again later!\n";
  exit 1;
}

print "In File: $in. Out file: $out\n";

open (HEX, " < $in");
open (OUT, " > $out");

$oldY = '';
$start = 0;

print OUT "module $file(input [14:0] ADDR, input CLOCK50, output reg [2:0] color);\nalways @ (posedge CLOCK50)\n";

while ( $line = <HEX> ) {
 if (length($line) == 14) {
 if (substr($line, 10, 1) ne 0) {

  $Y = substr ($line, 3, 2);
  $X = substr($line, 5, 2);
  if ($oldY ne $Y) {
   $oldY = $Y;
   if ($start == 1) {
     print OUT "\t\telse color = 3'b0;\n";
     print OUT "\tend\n";
     print OUT "\telse ";
   } else { $start = 1; }
   print OUT "\tif ( ADDR[14:8] == 7'h$Y )\n\tbegin\n";
   print OUT "\t\tif (ADDR[7:0] == 8'h$X)\n";
  } else {
   print OUT "\t\telse if ( ADDR[7:0] == 8'h$X )\n";
  }
  print OUT "\t\t\tcolor = 3'd" . substr($line, 10, 1) . ";\n";
 }} else {
  $len = length $line;
  print "An input line was size $len .\nLine contents:[$line]\n";
  print "All lines are supposed to be 13 chars long! (As generated by Quartus)\n";
 }
}

print OUT "\t\telse color = 3'b0;\n\t";
print OUT "end\n\telse color <= 3'b0;\nendmodule\n";

close OUT; close MIF; 
