#!/usr/local/bin/perl
# NOTE THE ABOVE LINE: IT MUST CONTAIN THE PATH TO PERL ON YOUR SYSTEM
#
# txtindex - make index.txt, a keyword-based index to other .txt files
#
# This program, given a file with a list of keywords and another file(s)
# containing MUSH help entries, reports all help subjects containing the
# given keyword (a keyword can contain spaces).
# The search is case insensitive.
#
# First, make a file containing a list of 'keywords' that you want indexed.
# Then run this little program giving it at least two arguments:
# the file of keys, and the help file(s).
#
# Example:
#    Call this program "ref.pl"
#    Call the key file "keys"
#    Then type "ref.pl keys events.txt help.txt > index.txt"
#
# Originally coded by Schmidt@DuneII
# This version, by Paul@DuneII, should be much faster, should handle
#  cases which the original did not (keyword followed by , etc.),
#  allows multiple .txt files to be searched at once, and produces
#  output suitable for another 'help'-type command, noting the
#  location and name of each entry (i.e. "help combat" or "news dune")
#
 
die "Usage: $0 keyword-file .txt-file(s)\n" unless $#ARGV > 0;
$keyfile=shift(@ARGV);
@inputfiles=@ARGV;
 
# Read in the whole keylist, and build a big perl program in
# $findkeys which adds an entry into the %refs associative
# array (indexed by keyword) if the $text string contains the
# keyword.
$findkeys =<<END;
  while (<INP>) {
    chop; tr/[A-Z]/[a-z]/;
    if (/^& *(.*)/) {
      \$newname = \$1;
      if (\$topics) {
END
die "Could not open $keyfile\n" unless open(KEY,$keyfile);
while ($word = <KEY>) {
 next if $word =~ /^$/;  # Ignore blank lines for formatting
 chop($word);
 $find .= "\$refs{\"$word\"} .= \$type . \$name . \"\\n\"
      if (\$text =~ /\\b$word\\b/oi);";
}
close(KEY);
$findkeys .= $find;
$findkeys .=<<END;
   }
   \$topics++;
   \$name = \$text = \$newname;
  } else {
   \$text .= " " . \$_;
  }
 }
END
$findkeys .= $find;
 
# Ok, now we go through each input file
foreach $file (@inputfiles) {
    warn "Unable to process $file\n", next unless open(INP,$file);
    $type = $file; $type =~ s/.txt/ /;
    push (@types,$type);
    $topics = 0;
    eval $findkeys;
    $topics++;
    print STDERR "Read $topics topics from $file...\n";
}

# Header for the output 
print "& help\n";
print "To find all entries in ", join(", ", grep(s/ $//,@types)),"\n";
print "which pertain to a keyword, type 'index <keyword>'.\n\n";

# Now, write the output, which is all in %refs.
foreach (sort keys %refs) {
    print "& $_\n",$refs{$_},"\n";
}
 
print STDERR "Done!\n";

