#!/usr/bin/perl

#
# Read a set of .doc files generated by CUPL,
# outputting a list of trivial variables.
#

# BUGBUG: Don't report type "V".

foreach $f (@ARGV) {
  %io = %lh = %rh = ();
  open(INPUT, $f) || die "$f: $!";
  %pad = ();
  while (<INPUT>) {
    last if /^--- --/;
  }
  while (<INPUT>) {
    next unless /^\s+([!]*)\s+(\S+)\s+(\S+)\s+[V]/;
    $io{$2} = 1;
    $rh{$2} = 1;
  }
  open(INPUT, $f) || die "$f: $!";
  $name = $f; $name =~ s/.doc$//;
  $name =~ s/.*[\\\/]//;
  $name = "dec$name" if $name =~ /^23/;
  $name = "sn$name" if $name =~ /^74/;
  $name =~ y/A-Z/a-z/;
  while (<INPUT>) {
    last if /^====/;
  }
  while (<INPUT>) {
    last if /^====/;
  }
  while (<INPUT>) {
    s/\r//g;
    last if /^====/;
    if (/^(\S+)\s*=>/) {
      $lh = $1;
      $negate = ($lh =~ s/^!//);
      $suffix = "";
      $suffix = $1 if $lh =~ s/(\..*)//;
      $io{$lh} = 1 if $suffix ne ""; 
      $lh{$lh} = 0; 
    } elsif (/^\r*$/) {
    } else {
      next unless defined $lh;
      while (s/(\w+)//) {
        $rh{$1} = 1;
        $lh{$lh}++;
      }
    }
  }
  $count = 0;
  $dead = 0;
  foreach $lh (sort keys %lh) {
    $count++;
#next if $io{$lh};
    next if $lh =~ /[.]oe$/;
#   print "$name: $lh has $lh{$lh} terms\n" if $lh{$lh} < 2;
    $dead++;
#next;
    next if defined $rh{$lh};
    print "$name: $lh is unreferenced with $lh{$lh} terms\n";
  }
  print "$name: $count signals, $dead unreferenced\n";
}
