#!/usr/local/bin/perl
while (<>) {    # the first pass takes the input from STDIN
        if (/^@(defn|use)\s(.*)$/) { # we've found a name of some sort
          if (($truncated = $2) =~ s/\.\.\.$//) { # this one ends in dots.
                $completion{$truncated} ="incomplete";
                $truncations{$.-1} = $truncated;
                $usage_type{$.-1} = $1;
                }
          else {$completion{$2} ="complete";}
          }
          push(lines,$_);

}
@namelist = sort(keys(%completion));
$j = $i = 0;
while ($i < $#namelist) { #collect all the ambiguities in a row
  while ($completion{$namelist[$j]} eq "incomplete") {
     $ambiguity_found = 1;
     $j = $i + 1; 
  }     
  if (defined $ambiguity_found) {
     $suggested = $namelist[$j]; 
     $nextchance =  $namelist[$j+1];
     foreach $name (@namelist[$i..$j-1]) { 
       if (substr($suggested,0,length($name)) ne $name) {
           die "FATAL ERROR: can't resolve <<$name...>>\n"
       }
     }
     if ($completion{$nextchance} eq "complete") {
       foreach $name (@namelist[$i..$j-1]) { 
         if (substr($nextchance,0,length($name)) eq $name) {
            print STDERR "WARNING--Ambiguous chunkname:\n";
            print STDERR "\t could be either\n";
            print STDERR "\t or\n\t\n";
            print STDERR "I will use \n"
         }
       }
     }
  }  
  foreach $name (@namelist[$i..$j]) { 
        $completion{$name} = $namelist[$j];
  }
  $j=$i=$j + 1; 
  undef($ambiguity_found);
}
foreach $trunc_line (sort(keys(%truncations))) {
  $lines[$trunc_line] = 
        "\@$usage_type{$trunc_line} $completion{$truncations{$trunc_line}}\n";
}
print @lines;
