#  A simple interface to search the MITSFS pinkdex.
#  Calvin Clark <ckclark@mit.edu>
# 
#  $Header: /afs/athena.mit.edu/user/c/k/ckclark/home/sipb/src/perl/RCS/pinkdex.pl,v 1.1 1993/08/23 22:32:03 ckclark Exp ckclark $

# $map{'pinkdex'} = '&do_pinkdex ("$rest?$query")';

$pinkdex_file = "/afs/athena.mit.edu/user/m/i/mitsfs/Public/pinkdex.txt";

sub info {
    print <<"EndOfInfo";
<TITLE>MITSFS Library Pinkdex</TITLE>
<ISINDEX><h1>MITSFS Library Pinkdex</h1>
<p>
This is a simple interface to search the MIT Science Fiction Library's
catalog.  You can search by author or by title.  Matches are case insensitive.
Examples: <p>
<ul>
<li> An author search: <p>
<code>author zelazny</code><p>
<li> A title search:  Don't try to quote any spaces or characters; everything
after title or author is passed as a single token. <p>
<code>title foundation and empire</code><p>
<li> A more specific author search: <p>
<code>author adams, douglas</code><p>
<li> A regular expression title search: <p>
<code>title \\[gor 2[0-9]\\]</code><p>
<p>
</ul>
<img src="/afs/sipb.mit.edu/user/ckclark/html/bug.xbm"> eats up the +'s in your
regexps <p>
EndOfInfo
}

sub do_pinkdex {
    local ($args) = @_;
    local (*PINKDEX);
    local ($type, $regexp);
    local ($match);
    local ($regexp1, $regexp2);
    local ($query);

    $args =~ /\?(.+)/;
    $query = $1;
    $query =~ y/\+/ /;

    if (! $query) {
	&info;
	return;
    }
   
    ($type, $regexp) = split (/ +/, $query, 2);

    eval { /$regexp/ };
    if ($@ ne "") {
	&error('bad_request', "error in regular expression: $@");
    }

    $type =~ y/A-Z/a-z/;

    if ($type eq "author") {
	$regexp1 = ".*$regexp.*";
	$regexp2 = ".*";
    }
    else { 
	if ($type eq "title") {
	    $regexp1 = ".*";
	    $regexp2 = ".*$regexp.*";
	} 
	else {
	    &error ('bad_request', 'you must specify author or title search');
	}
    }

    alarm ($time_out);

    open (PINKDEX, "<$pinkdex_file") 
	|| &error ('internal_error', "error opening $pinkdex_file: $!");

    print "<h1>$type search: $regexp</h1><p>\n";
    print "<ISINDEX><pre>\n";
    while (<PINKDEX>) {
	if (/^($regexp1)<($regexp2)</oi) {
	    if ($match ne $1) {
		$match = $1;
		print "<h2>$match:</h2>\n";
	    }
	    print "\t$2\n";
	}
    }
    if (! $match) {
	print "<b>No matches found.</b><p>\n";
    }

    print "</pre>\n";
    close (PINKDEX);
    
    alarm (0);
}
1;
