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

sub usage { <<EOF
Usage: $0 [options] wordnum
	-h  This text
	-q  Quiet (don't repeat input)
	-r  Reverse lookup (arg is word, not num)
EOF
}

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

my %opt;
getopts('rqh', \%opt);
$opt{h} && die usage();

open (WORDS, find('pSgT.txt')) or die "Can't open pSgT.txt, aborting";
$empty = <WORDS>;
$numwords = <WORDS>;
$empty = <WORDS>;

my @words, %words;
while (<WORDS>) {
  chomp;
  s/\s+.*$//;
  push @words, $_;
  $words{$_} = $#words;
}

if (@ARGV and $ARGV[0] > 0) {
  foreach my $wordnum (@ARGV) {
    my $outword = $opt{r}? $words{$wordnum}: $words[$wordnum];
    if ($opt{q}) {
      print $outword, "\n";
    } else {
      printf "%5d %s\n", $wordnum, $outword;
    }
  }
} else {
  while (<>) {
    #printf "%5d %s\n", $_, $words[$_];
    print, next if /^\s*\#/;
    chomp;
    my $outword = $opt{r}? $words{$_}: $words[$_];
    if ($opt{q}) {
      print $outword, "\n";
    } else {
      printf "%s %s\n", $_, $outword;
    }
  }
}
