#!/usr/local/bin/perl -w
use Getopt::Std;

my $usage = "Usage: $0 [options] conditioned featval [featval [...]]\n" .
  "  conditioned\tID of conditioned event (e.g. g, m, ff)\n" .
  "  featval\tnumeric values of features according to trees\n\n" .
  "  -a\tprint probabilities at all depths\n" .
  "  -b\tprocess from batch file(s), or stdin if none provided\n" .
  "  -v\tgive verbose output (interpret numbers)\n" .
  "\n";

my %opt;
getopts("abv", \%opt);

$find = sub { shift };
my $dir = $0;
$dir =~ s#/\w+$#/#;
eval { require "$dir/utils.pm"; };

if ($opt{b}) {
  while (<>) {
    print, next if /^[\#\s(]/;
    itprob (split);
  }
} else {
  my $feature = shift or die $usage;
  itprob($feature, @ARGV);
}

sub numword {
  my $num = shift;
  return $num unless $opt{v};
  our %numhash;
  if (exists($numhash{$num})) {
    return $numhash{$num};
  } elsif ($num eq 'A') {
    return "A/Alt-branch";
  } else {
    $numhash{$num} = $num;
    return $numhash{$num} if ($num >= @wordname);
    $numhash{$num} .= "/" . $wordname[$num];
    return $numhash{$num} if ($num >= @termname);
    $numhash{$num} .= "/" . $termname[$num];
    return $numhash{$num} if ($num >= @funcname);
    $numhash{$num} .= "/" . $funcname[$num];
    return $numhash{$num};
  }
}

sub expand {
  my $line = shift;

  return $line unless $opt{v};
  $line =~ /^\s*(\d+)\s*([\d.e-]+)/ or return $line;
  my $extra = numword($1);
  $extra = ("\t" . $extra)  if length($2) < 8;
  chomp $line;
  $line =~ s/^(\t+)/"    "x length($1)/e;
  return $line . $extra . "\n";
}

sub itprob {
  my ($feature, @atts) = @_;
  my $feattree = $feature;
  open (G, &{$find}("$feature.g")) or die "Can't open $feature.g, aborting";
  my $lastseek = 0;
  my $depth = 0;
  ATT:
  foreach my $att (@atts) {
    $feattree .= " " . numword($att);
    --$depth if $att eq 'A';
    my $search = '^(?:' . '\t' x ($depth) . $att . '\s' .
		  ($depth ? '|(' . '\t' x ($depth-1) . '\S)' : '') . ')';
    #print $search, "\n";
    while (<G>) {
      next unless /$search/;
      #print;
      last ATT if $1;
      $lastseek = tell unless $att eq 'A';
      print $feattree, "\n";
      print "Line #$.:\t";
      print expand($_);
      if ($att ne 'A') {
	do { $_ = <G>; print expand($_) if $opt{a}; } until /^\s*$/g;
      }
      last;
    }
    ++$depth;
  }

  if (!$opt{a}) {
    print "Probabilities: \n";
    seek G, $lastseek, 0;
    while (<G>) {
      last if /^\s*$/;
      print "\t\t";
      print;
    }
  }
  close G;
}
