#!/usr/bin/perl -W

# show the difference between two 'tables.txt' files

if (@ARGV != 2) {
    print "usage:\n";
    print "\t diff_table.pl old-table new-table\n\n";
    exit;
}

%tbl1 = read_table($ARGV[0]);
%tbl2 = read_table($ARGV[1]);

$prevkey="";
foreach $n (sort keys %tbl1) {
    if (defined($tbl2{$n})) {

	$n =~ /^(\w+)\[/; # insert linebreaks between different tables
	if ($prevkey ne $1) {
	    $prevkey = $1;
	    print "\n";
	}

	print "$n=";
	print diff_line($tbl1{$n}, $tbl2{$n}) . "\n";
    } else {
	print "'$n' not found in file $ARGV[1]\n";
    }

}


sub diff_line
{
    my $line1 = shift @_;
    my $line2 = shift @_;

    @values1 = split / /, $line1;
    @values2 = split / /, $line2;
    
    my $diff = "";
    for ($i=0; $i<=$#values1; $i++) {
#	$diff .= hex($values1[$i])-hex($values2[$i]) . " ";
	printf("%3d ", hex($values2[$i])-hex($values1[$i]));
#	printf("%02X ", hex($values1[$i])-hex($values2[$i]));
    }
    return $diff;
}



sub read_table
{
    my $fname = shift @_;
    my %tbl;

    open(FILE, "<$fname") or die "can't open $fname";

    while($l = <FILE>) {
	chomp $l;

	if ($l =~ /^\s*($|\/\/|\#|;)/) {  # skip lines consisting of comments only
	    next;
	}
    
	if ($l =~ /(\w\[\w\])=(.+)/) {  # search for j[0]=
	    $array_name = $1;
	    $values = $2;
	    
	    if ($array_name =~ /[njrklh]/) {
		$tbl{$array_name} = $values;
	    } else {
		print STDERR "unrecognised array \"$array_name\", ignoring\n";
	    }
	}
    }
    
    close FILE;
    return %tbl;
}


