#! /usr/bin/perl
###############################################################################
#
# Site search interface
#
# Written by Behan Webster <behanw@pobox.com>
# Copyright (c) 1996 by Brian White and Behan Webster
#
###############################################################################


require query;

###########################################################################
# Parse the command arguments
#
if ($#ARGV<0) {
	if ($ENV{'QUERY_STRING'}) {
		#
		# Read key pairs from the get
		#
		splitPairs($ENV{'QUERY_STRING'});
		$level	 = $FORM{'l'};
		$page	 = $FORM{'p'};
		$display = $FORM{'d'};
		$number	 = $FORM{'n'};
		$query	 = $FORM{'q'};
        $type	 = $FORM{'t'};
	}
} else {
	#
	# Read the argument list from the command line
	#
	($level, $page, $display, $number, @query) = @ARGV;
	$type	= pop(@query) if ($level !~ /^a/io);
	$query	= join(' ', @query);
}

# If level is "advanced"
if ($level =~ /^a/io) {
	$oldquery =  $query;
}

$query    =  unarmorURL ($query);

# If level is "simple"
if ($level !~ /^a/io) {
	$query    =~ tr/"//d; #"
	$query    =~ tr/ !|&0-9/ /s;

	#
	# Set to defaults if these are undefined
	#
	$type    = "p"  if !$type;
	$oldquery =  "$query+$type";

	#
	# Put together the query
	#
	if ($type =~ /^a/i) {
	    # The format is already correct for this option

	} elsif ($type =~ /^o/i) {
		$query = join(' | ', split(/\s+/, $query)) if $query;

	} else { # Search for a phrase is the default
		$query = qq{"$query"} if $query;
	}
}

$oldquery =~ tr/ /+/;

#
# Set to defaults if these are undefined
#
$display = "s"  if (!$display | !$query);
$number  = -1   if $number =~ /^(all|\*)$/io;
$page    =  1   if !$page | $number <= 0;
$number  = 15   if !$number | $number =~ /^$/ | $number !~ /[0-9]/;

#
# Print help file if it's been requested
#
if ($FORM{'help'}) {
    filePage($helpfile);
    exit;
}

#
# Perform the query
#
$search  = openIndex();
@results = $search->Query($query);

#
# See if the query failed
#
if ($@) {
	errorPage($query, $@);

} else {

	#
	# Load the site file
	#
	$_ = Ferret::LoadFile($sitePage);
	/^(.*)$resultsIns(.*)$/s;
	my $after = $2;

	#
	# Print the first bit of the site file
	#
	print "$1\n";

	#
	# Print kind of output
	#
	resultsTitle($display);

	#
	# Print page number and number of results
	#
	pageNumber($page, $number, $#results+1);

	#
	# Skip the first pages
	#
	for(1..($page-1)*$number) {
		shift @results;
	}

	#
	# Allow the user to go to the previous results in the list
	#
	prevPage($searchCgi, $level, $page, $display, $number, $oldquery);

	#
	# Display the list (compact or summary)
	#
	if ($display =~ /^c/io) {
		compactList("", $query);
	} else { # $display="s" is the default
		summaryList("", $query);
	}

	#
	# Allow the user to go to the next results in the list
	#
	nextPage($searchCgi, $level, $page, $display, $number, $oldquery, $#results+1);

	#
	# Print the last bit of the site file
	#
	print "\n<br><br>\n$after";

}
