#!/usr/bin/perl

# $rcs = ' $Id: search.cgi,v 1.4 1998/06/20 07:15:03 fitz Exp $ ' ;

unshift(@INC, "lib");

require 'config.pl';
require 'bib.pl';
require 'db.pl';
require 'web.pl';
require 'cgi-lib.pl';

print "Content-type: text/html\n\n";
&ReadParse();

if ($ENV{PATH_INFO})
{
    unless ($in{q})
    {
        ($in{q} = $ENV{PATH_INFO}) =~ s!.*/!!;
    }
}

&error("No search query was specified.") unless %in;

# Initially consider all IDs as "hits"
foreach (&db::get_ids())
{
    $hits{$_} = 1;
}

if ($in{q})
{
    if ($in{exact})
    {
        $query = $in{q};
        $in{q} =~ s/(\W)/\\\1/g;
        $words[0] = $in{q};
    }
    else
    {
        $in{q} =~ s/\W+/ /g;
        @words = split(/\s+/, $in{q});
        $query = "$in{q}";
    }
}

if ($in{keyword})
{
    $query = "keyword=$in{keyword}";
    $in{keyword} =~ s/(\W)/\\\1/g;

    $in{q} = 'bogus';
    $words[0] = $in{q};
}

foreach $word (@words)
{
 ID:
    foreach $id (keys %hits)
    {
        %entry = &db::read_entry($id);

        $hits{$id} = $entry{TITLE};
        $author{$id} = $entry{AUTHOR};

        if ($in{keyword})
        {
            delete($hits{$id})
              unless $entry{KEYWORDS} =~ /\b$in{keyword}\b/i;
            next ID;
        }

        # Search the entry - it must contain the word or we remove
        # this ID from the hit list
        foreach $key (keys %entry)
        {
            next ID if $entry{$key} =~ /$word/i;
        }

        # Remove the ID from the hits list
        delete $hits{$id};
    }
}

foreach $id (sort id_by_title keys %hits)
{
    $series .= "$id,";
    $bib::db{$id}->{TITLE} = $hits{$id};
    $bib::db{$id}->{AUTHOR} = $author{$id};

    $list_items .= "<LI> " . &bib::link_to_id($id);
}

&error("No hits for search query '<STRONG>", &untaint($query), "</STRONG>'")
  unless $list_items;

# Create the HTML page
$data = &bib::template("search.html",
                       "HITS", $list_items,
                       "QUERY", $query,
                       "SERIES", $series,
                       "HEADING", "Search for: " . &untaint($query));

print &bib::template("basic.html",
                     "TITLE", "Search Results",
                     "DATA", $data,);

exit 0;


sub id_by_title
# Given a database ID, sort by the corresponding title
{
    my($a2, $b2);

    # Remove "The" or "A" from the start of the title
    ($a2 = $hits{$a}) =~ s/^(the|a)\b\s*//i;
    ($b2 = $hits{$b}) =~ s/^(the|a)\b\s*//i;

    uc($a2) cmp uc($b2);
}
