#!/usr/bin/perl -W

# script to convert tables.txt into a gnuplot friendly format

# in gnuplot interactive mode, type:
#   set parametric
#   set xlabel "rpm"
#   set ylabel "kpa"
#   set zlabel "ve"
#   splot 'name_of_file_containing_the_output_of_this_script' with lines


sub usage {
    print "usage:\n";
    print "\t to_gnuplot.pl which_table tables.txt\n\n";
    exit;
}


if (@ARGV != 2) {
    usage();
}

$tbl = shift @ARGV;
if ($tbl !~ /[jnl]/) {   # any table we know?
    usage();
}

open(GLOBAL, "<$ARGV[0]") or die "can't open $ARGV[0]";

@g = <GLOBAL>;
close GLOBAL;

# first iteration: find rpm and kpa table
foreach $l (@g) {
    chomp $l;

    if ($l =~ /^\s*($|\/\/)/) {  # skip lines consisting of comments only
	next;
    }
    
    if ($l =~ /(\w)\[(\w)\]=(.+)/) {  # search for j[0]=
	@values = split / /, $3;
	$array_name = $1;
	$index = $2;

	if ($array_name =~ /r/) {
	    for ($i=0; $i<@values; $i++) {
		$rpm[$i] = hex($values[$i]);
	    }
	} elsif ($array_name =~ /k/) {
	    for ($i=0; $i<@values; $i++) {
		$kpa[$i] = hex($values[$i]);
	    }
	}

	if ($array_name !~ /[njrkl]/) {
	    print STDERR "unrecognised array \"$array_name\", ignoring\n";
	}
    }
}

# second iteration: find the table we want
foreach $l (@g) {
    chomp $l;

    if ($l =~ /^\s*($|\/\/)/) {  # skip lines consisting of comments only
	next;
    }
    
    if ($l =~ /(\w)\[(\w)\]=(.+)/) {  # search for j[0]=
	@values = split / /, $3;
	$array_name = $1;
	$index = $2;

	if ($array_name =~ /$tbl/) {
	    for ($i=0; $i<@values; $i++) {
		printf("%d\t%d\t%d\n", $rpm[$i], $kpa[$index], hex($values[$i]));
	    }
	    print "\n";
	}
    }
}

