#! /usr/bin/perl -w
# gridstate <file>

#  reads <file> which is triples where the second member is a state
#  value.  For N distinct values in the file,
#  make a sorted table of the N values, and rewrite as <file>.norm with
#  grid spacing at these values.
#

$file = $ARGV[0];
die "Can't find the plot file",$file unless (-e $file);
$outfile = $file.".norm";
system "sort -n $file > $outfile"; #on first, input, field
system "sort -n +1 +0 $outfile >$file.sort"; #on state, second, field, now tidy
$file = $file.".sort";
$com ="gawk '{print \$2}' $file |sort -u -n";

$baz = `$com`;
@StateList = split("\n",$baz);
print "The list of state values is:\n";
foreach $i(@StateList) {print "$i ";} print "\n";
print "continue? [Enter or ^C]";
$stopflag = <STDIN>; 

$stopflag = 0;
$which = 1;
AGAIN:
open(PF,"<$file");
open(PFF,">$outfile") or die "Can't create output file";
$whichState = 0;
while ($line = <PF>) {
  @triple = split(" ",$line);
  if ($whichState == 0 || $curState != $triple[$which]) { #first or new state value
    if ($whichState == 0) {
      $whichState = 1;
    } else {
      if ($which == 1) { #doing input states
        print PFF "\n"; #for grid spacing
      }
    }
    $curState = $triple[$which];
  } 
  print PFF "$triple[0] $triple[1] $triple[2]\n";
}
close(PF);
close(PFF);

