#!/usr/bin/perl

# This CGI program runs on the Unix web server to provide random text for
# the Java applet, which runs in the browser.  This program requires two
# facilities present on the Unix system: the "yow" database, which contains
# random quotations from Zippy the Pinhead, and the /usr/dict/words file,
# which contains a long list of English words.
#
# The Java applet calls this CGI program without a query string if it wants
# to fetch a random quotation or with a query string containing the list of
# letters the user requested if it wants to get some random words containing
# only those letters.

use FileHandle;

print "Content-type: text/plain\n";
print "Cache-control: no-cache\n";
print "\n";

$letters = $ENV{'QUERY_STRING'};

if ($letters eq '') {
    # Quotation requested, pull one out of the "yow" database.

    $/ = "\000";
    open(LINES, '</www/htdocs/yow.lines') || die;
    @lines = <LINES>;
    close(LINES);
    $/ = "\n";

    shift @lines;
    $line = $lines[rand(@lines)];
    chop($line);
    $line =~ s/^\n//;
    print $line, "\n";
    exit 0;
}

# Random words requested.  Read the /usr/dict/words file and build a list
# of all the words that contain only the requested letters.  Only use words
# that have 3 or more letters.

open(WORDS, '</usr/dict/words') || die;
@words = grep(/^[$letters]{3,}$/i, <WORDS>);
close(WORDS);

# Now build up a string containing random entries from the word list, and send
# the resulting string to the applet.

$string = '';

srand(time ^ $$);

while (length($string) < 250) {
    $word = $words[rand(@words)];
    $word =~ s/[\n ]*$/ /;
    $string .= $word;
}

$string =~ s/\s*$/\n/;
print $string;

exit 0;
