#!/usr/bin/perl -w
# -T can only be given on the command line (taint checking)
use strict; # homework by Eric Auer...

use vars qw/%H/; # could be a list: make those very global

my $SHOWINDEX = 0; # set to 1 to print the hash (big...)
my %H;           # the main hash

sub readindex {
  open (IFILE,"<index.txt") || die "Cannot read index.txt\n";
  my @ilines = <IFILE>;
  close(IFILE);
  my $terms = 0;
  my $iline;
  foreach $iline (@ilines) {
    unless ($iline =~ /;.*,/) { next; } # skip too weird lines
    chomp $iline; # kind of important...
    $terms++;
    $iline =~ tr/\007/:/; # make our special char user-friendly
    my $iword;
    my @iwhere;
    ($iword,@iwhere) = split(/;/,$iline); # first parse step
    my $iwhere2;
    foreach $iwhere2 (@iwhere) {
      my $ifile;
      my @iposn;
      ($ifile,@iposn) = split(/,/,$iwhere2); # second parse step
      $H{$iword}->{$ifile} = join(",",@iposn); # the big hash!
    }
  }
  return $terms;
}


sub showindex {
  foreach my $oneword (sort keys %H) {
    printf "\n%20s: ", $oneword;
    foreach my $item (sort keys %{$H{$oneword}}) {
      print "<\"$item\"," . $H{$oneword}->{$item} . "> ";
    }
  }
}


sub reftoindex {
  return \%H;
}


print "loading index...\n";
print "" . &readindex() . " terms loaded\n";
if ($SHOWINDEX == 1) { &showindex }

# $H{'ping'}->{'pong'} = "foo";
# print "$H{'ping'}->{'pong'}";
# print "\nend of query-read\n";

return 1; # if we were "required", tell that we succeeded

