#!/s/perl/bin/perl

# The directory where the bib files are stored

$dir = '/u/d/e/deboor/public/html/bib';


# Turn off buffering on stdin and stdout

$| = 1;


# Copy the contents of the environmental variable QUERY_STRING into $QS. If
# the former is empty, print out the HTML start page and exit

if (! ($QS = $ENV{QUERY_STRING}) ) {
  print "Content-type:  text/html

<HTML>
<HEAD>
<TITLE>Reference Search Page</TITLE>
</HEAD>
<BODY>

<H2>Reference Search</H2>

<P> This is the search page for the de Boor/Schumaker Spline Bibliography.
Enter a search term (in the form of a perl regular expression) followed by 
[enter], to search the records (and be prepared to wait for about one minute 
for the results). Each bib item is treated as one string.
<P> <ISINDEX>
</BODY>
</HTML>
";
  exit;
}


# Spaces become pluses in URLs, so put them back

$QS =~ s/\+/ /g;

# Special characters are encoded as "%hh", where h is a hexidecimal digit
# This stanza decodes all such occurrences.

$QS =~ s/%(..)/pack("c",hex($1))/ge;


# We also print the search string, so we need to replace the special HTML
# characters with their entity counter-parts.

$printQS = $QS;
$printQS =~ s/&/&amp;/g;
$printQS =~ s/</&lt;/g;
$printQS =~ s/>/&gt;/g;


# Print the start of the search result page

print "Content-type: text/html

<HTML>
<HEAD>
<TITLE>Search Results</TITLE>
</HEAD>
<BODY>

<H2>Search Results</H2>

<P> Here are all the references matching the pattern <EM>$printQS</EM>.

<TT>";


# $records will store the number of references printed (actually, the number
# of matches in records as things stand below).

$records = 0;

# Step through each filename
for ($let = 'A'; $let le 'Z'; $let++) {
  open BIBFILE, "$dir/$let";   # open the current file
  while (<BIBFILE>) {          # read every line in the file into $_
    if (/^\s*$/) {             # If it's nothing, or whitespace
      $entry =~ s/&/&amp;/g;
      $entry =~ s/>/&gt;/g;
      $entry =~ s/</&lt;/g;
      $entry =~ s/\n/<BR>/g;
      if ($entry =~ /$QS/) {   # and if we were going to print the last entry
        print "<P> $entry\n";      # print it
        $records++
      }
      $entry = '';             # We're on a blank line, so start a new entry
    } else {
      $entry .= $_;            # Add the current line onto $entry
    }
  }
  if ($entry =~ /$QS/) {       # Print the entry if there's no blank line
    $entry =~ s/&/&amp;/g;
    $entry =~ s/>/&gt;/g;
    $entry =~ s/</&lt;/g;
    $entry =~ s/\n/<BR>/g;
    print "<P> $entry\n";          # at the end of the references file
    $records++
  }
  close BIBFILE;
}


if (! $records) {              # If no matches were found, print a message
  print "Sorry, no matches were found.\n";
}


# Finish up the file by closing all open elements.

print "<P> </TT> $records lines contained the given pattern \n</BODY></HTML>\n";
