#!/usr/bin/perl

if (@ARGV!=2) 
{
  die("Usage : lookup_table inputfile mif-file\n");
}

$cond_aktiv=0;

open(inputfile,$ARGV[0]) || die("Could not open file $ARGV[0]\n");

# parse inputfile
while (<inputfile>)
  {
    if ($cond_aktiv==0)
      {
	# nicht innerhalb des COND
	if (/COND/==1) # is this line the beginning of a COND?
	  {
	    $cond_aktiv=1;
	  }
      }
    else
      {
	# innerhalb des COND
	if (/ENDCOND/==1) # is this the last line of the COND?
	  {
	    $cond_aktiv=0;
	  }
	else
	  {
	    # really inside the COND
	    @spalte=split(","); # split lines at ','
	    chomp(@spalte); # remove line endings

	    for ($i=0;$i<@spalte;$i++)
	      {		
		if (length($spalte[$i])>0) # select only not empty lines
		  {
		    @temp1=split("->",$spalte[$i]);
		    $left=$temp1[0];
		    $right=$temp1[1];

		    @temp2=split("=",$left);
		    $number=$temp2[1]; # number after 'i='
		    
		    @temp3=split(" ",$right);
		    $hex1=$temp3[0];
		    $hex2=$temp3[2];

		    if ($hex1 eq "h0") { $bits1="0000"; }
		    if ($hex1 eq "h1") { $bits1="0001"; }
		    if ($hex1 eq "h2") { $bits1="0010"; }
		    if ($hex1 eq "h3") { $bits1="0011"; }
		    if ($hex1 eq "h4") { $bits1="0100"; }
		    if ($hex1 eq "h5") { $bits1="0101"; }
		    if ($hex1 eq "h6") { $bits1="0110"; }
		    if ($hex1 eq "h7") { $bits1="0111"; }
		    if ($hex1 eq "h8") { $bits1="1000"; }
		    if ($hex1 eq "h9") { $bits1="1001"; }
		    if ($hex1 eq "hA") { $bits1="1010"; }
		    if ($hex1 eq "hB") { $bits1="1011"; }
		    if ($hex1 eq "hC") { $bits1="1100"; }
		    if ($hex1 eq "hD") { $bits1="1101"; }
		    if ($hex1 eq "hE") { $bits1="1110"; }
		    if ($hex1 eq "hF") { $bits1="1111"; }

		    if ($hex2 eq "h0") { $bits2="0000"; }
		    if ($hex2 eq "h1") { $bits2="0001"; }
		    if ($hex2 eq "h2") { $bits2="0010"; }
		    if ($hex2 eq "h3") { $bits2="0011"; }
		    if ($hex2 eq "h4") { $bits2="0100"; }
		    if ($hex2 eq "h5") { $bits2="0101"; }
		    if ($hex2 eq "h6") { $bits2="0110"; }
		    if ($hex2 eq "h7") { $bits2="0111"; }
		    if ($hex2 eq "h8") { $bits2="1000"; }
		    if ($hex2 eq "h9") { $bits2="1001"; }
		    if ($hex2 eq "hA") { $bits2="1010"; }
		    if ($hex2 eq "hB") { $bits2="1011"; }
		    if ($hex2 eq "hC") { $bits2="1100"; }
		    if ($hex2 eq "hD") { $bits2="1101"; }
		    if ($hex2 eq "hE") { $bits2="1110"; }
		    if ($hex2 eq "hF") { $bits2="1111"; }
		    
		    $bits="$bits1$bits2";
		    
		    $bittabelle[$number]=$bits;
		  }
	      }
	  }
      }
  }

close(inputfile);

# create output-file
open(outputfile,"+>$ARGV[1]") || die("Could not create file $ARGV[1]\n");
for ($i=0;$i<256;$i++)
  {
    print outputfile "$bittabelle[$i]\n";
  }
close(outputfile);
