#!/usr/planet/bin/perl5

require("include/bbn.pm");

########################################################################
# Constants for use in this script

  $SWISH = "./swish/swish" ;

  $SCRIPT = "/$SCRIPT_DIR/$MASH_SCRIPT";
  $LINE_IMG = "/$IMAGE_DIR/line1.gif";

  $SMALLHITS = 6 ; # number of hits required to make a chunk table
  
  # Do standard CGI stuff
  &cgi_receive;
  &cgi_decode;

  $SID = $FORM{'session'} ;
  $INDEX = "./swish/swish.$FORM{'dir'}.index" ;
  open(DIRF,">$SESSION_PATH$SID/curdir");
  print DIRF "$FORM{'dir'}";
  close DIRF;

  $TBLS = -e "$SESSION_PATH$FORM{'session'}/hastables";
  
  if ($FORM{'page'}) {
     $P = $FORM{'page'} ;
  } else {
     $P = 0 ;
     $incoming = $incoming . "&page=0" ;
  }

  #Trap empty patterns to avoid big swish warning
  if ($FORM{'pattern'} eq '') {
    &do_no_query;
    exit;
  }

  #Escape any "*" wildcards so shell ignores them
  #$FORM{'pattern'} =~ s/\*/\\*/g;
  $FORM{'pattern'} =~ s/(\W)/\\$1/g;

  #But don't escape whitespace
  $FORM{'pattern'} =~ s/\\s/$1/g ;

  #put in parens 
  #$FORM{'pattern'} =~ s/ /) (/g ;
  #$FORM{'pattern'} = "($FORM{'pattern'})" ;

  #Add in the connector if it exists
  if ($FORM{'connect'}) {
    $FORM{'pattern'} =~ s/ / $FORM{'connect'} /g;
  }

  #=========================================================================
  #  Run Swish
  #=========================================================================

  @fnames = `$SWISH -f $INDEX $FORM{'swishopts'} -w $FORM{'pattern'} `;

  #If the full header didn't print, Swish failed
  if ($#fnames < 9) {
    &do_bad_return;
    exit;
  }

  shift(@fnames);	#Don't care about the format at this time

  # Reread the search pattern as SWISH saw it
  $FORM{'pattern'} = shift(@fnames);

  #But remove its header
  $FORM{'pattern'} =~ s/search words\: //;

  #Now eliminate all the remaining informational lines
  while (index($fnames[0], "#") != -1) {
    shift(@fnames);	
  }

  if ($fnames[0] =~ /^err/) {
    &do_err;
  }
  else {
    &do_return;
  }

  exit;

#=========================================================================
# gen html to return
#=========================================================================

sub do_return {

&cgi_header("CatoSearch Results");

chop(@fnames); # remove once and for all the \n after each file name

$#fnames--;       # we are going to sort, so ignore the "." line for now
@fnames2 = sort bytitle @fnames;
# launder the list to have only one occurrance of each unique file name
$pft = " ";
$#fnames = -1 ;
foreach $fn (@fnames2) {
   # replace any filename that ends in <n>.sub.html with prefix only
   $fn =~ s/\.\d\.sub\.html/\.html/ ;
   # split the line up into relevance, filename, title, bogon
   $fn =~ /^(\d+) (\S+) "(.+)" (\d+)/;
   #@ft = split(/"/,$fn) ;
   if ($pft ne $2) {
      $#fnames++ ;
      $fnames[$#fnames] = $fn ;
      $pft = $2 ;
   }
}
# put the "." line back
#$#fnames++ ;
#$fnames[$#fnames] = ".";
$nhits = $#fnames+1 ;

print <<EndOfStuff ;
<h1> 
<img src="/pix/ccs-ico.gif">
CatoSearch Results</h1>
<IMG SRC=\"$LINE_IMG\">
<br>
<b>$nhits companies matched your pattern: </b><i>$FORM{'pattern'}</i>
EndOfStuff

if ($FORM{'char'} eq "ALL" | $nhits < $SMALLHITS) {
  # generate the whole list
  print "<ul>\n";
  $cnt = 0;
  $lcnt = 0;
  foreach $fn (@fnames) {
    $fn =~ /^(\d+) (\S+) "(.+)" (\d+)/;
    $fc = substr($3,0,1);
    $fc = "\U$fc";
    $title = $3;
    $URL = substr($2,1);	## Remove the initial char. from $URL
    $cnt += 1;

    print qq|<a href="$SCRIPT/$SID/$URL?dir=$FORM{'dir'}"> |;
    &gen_one_logo;
    print " $cnt. $title </a>\n";
    if ($lcnt == $cnt) { print "<br>"; }
    print "<br> \n";
    }
  print "<br>\n";
  print "</ul>\n";

} elsif ($FORM{'char'}) {
  # generate small hitlist
  print "<br><i>Here are company listings for letter '$FORM{'char'}'</i>\n"; 
  print "<ul>\n";
  $cnt = 0;
  $lcnt = 0;
  foreach $fn (@fnames) {
    $fn =~ /^(\d+) (\S+) "(.+)" (\d+)/;
    $fc = substr($3,0,1);
    $fc = "\U$fc";
    if ($fc ne $FORM{'char'}) { next; }
    $title = $3;
    $URL = $2;
    $URL = substr($URL,1);	## Remove the initial char. from $URL
    $cnt += 1;
    print qq|<a href="$SCRIPT/$SID/$URL?dir=$FORM{'dir'}"> |;
    &gen_one_logo;
    print " $cnt. $title </a>\n";
    if ($lcnt == $cnt) { print "<br>"; }
    print "<br> \n";
    }
  print "</ul>\n";

} else {
  # generate the chunk ``table''
  print "<br><br>Select a letter of the alphabet to see company names,"; 
  print " or select a CatoSource Full Service company logo:\n";
  print "<center>\n";

  foreach $fn (@fnames) {
    $fn =~ /^(\d+) (\S+) "(.+)" (\d+)/;
    $fc = substr($3,0,1);
    $fc = "\U$fc";
    $hits{$fc} += 1 ;
    }
  @keys = keys %hits;
  @cnts = values %hits;
  if ($TBLS) {
  print "<br><table >";
  print "<tr>\n";
  print "<td align=center width=70><i>Co. name</i>";
  foreach $key (sort(keys %hits)) {
    print "<td width=15 align=center> $key";
    }
  print "<td align=center> <i>All hits</i>";
  print "\n<tr>\n";
  print "<td align=center width=50><i># hits</i>";
  $_ = $incoming ; s/char=$FORM{'char'}// ;
  foreach $key (sort(keys %hits)) {
    print "<td align=center> ";
    print "<a href=\"/cgi-bin/fullsearch?$_&char=$key\">$hits{$key}</a>";
    }
  print "<td width=15 align=center><a href=\"/cgi-bin/fullsearch?$_&char=ALL\">$nhits</a>";
  print "\n</table><br>\n";
  }  else { # do a non-table version
    $_ = $incoming ; s/char=$FORM{'char'}// ;
    print "<br><pre>\n";
    print "<i>Company name: </i>";
    foreach $key (sort(keys %hits)) {
      print "<a href=\"/cgi-bin/fullsearch?$_&char=$key\">$key</a> ";
    }
    print "(<a href=\"/cgi-bin/fullsearch?$_&char=ALL\"><i>All Hits</i></a>)";
    print "</pre>\n";
  }
   

  &gen_all_logos;

  print "</center>\n";
}

print "<br>";
print "<hr>";
print "<br>";
print "<center>";
print "<a href=\"/sessions/$FORM{'session'}/combined-ico.hit.map\">";
print "<img src=\"/pix/combined-ico.gif\" ISMAP></a>";
print "</center>\n";

&cgi_footer("hitlist");

}

sub gen_one_logo {
    $clifile = $CLIENT_PATH . "source/" . $URL ;
    if (!open(client, "<$clifile")) {
       print "Can't open client file $URL</body></html>";
       exit;
    }
    foreach (<client>) {
      if(/\/pix\/logo\/\S+\.gif/) {
	if ($cnt > ($lcnt+1)) { print "<br>"; }
	$thm = $& ; 
	$thm =~ s/\.gif$/\.thm\.gif/ ;
        print "<img src=\"$thm\" align=center border=1>";
	$lcnt = $cnt;
	last;
      }
    }
    close client;
    }

sub gen_all_logos {
  # find company logos and put to page
  foreach $fn (@fnames) {
    $fn =~ /^(\d+) (\S+) "(.+)" (\d+)/;
    $URL = substr($2,1);	## Remove the initial char. from $URL
    $clifile = $CLIENT_PATH . "source/" . $URL ;
    if (!open(client, "<$clifile")) {
       print "Can't open client file $URL</body></html>";
       exit;
       }
    foreach (<client>) {
       if(/\/pix\/logo\/\S+\.gif/) {
          print "<a href=\"$SCRIPT/$SID/$URL?dir=$FORM{'dir'}\">";
	  $thm = $& ; 
	  $thm =~ s/\.gif$/\.thm\.gif/ ;
          print "<img src=\"$thm\" align=center>";
	  print "</a>";
	  last;
       }

    }
    close client;
  }
}

sub bytitle {
   # expects to use by-reference strings $a and $b
   @aa = split(/"/,$a);
   @bb = split(/"/,$b);
   $aa[1] cmp $bb[1];
}



sub do_no_query {
  &cgi_header;
  print qq|<h2>No Query Specified</h2>\n|;
  print qq|<h3>You must specify something to search for.</h3>\n|;
  print qq|<p>Use <strong>Back</strong> to specify a different query,|;
  print qq| </A> or return to \n|;
 
  &print_overview;
  
  &cgi_footer;
}

sub do_err {
  &cgi_head;

  #scan through the array until we find the error message
  foreach $name (@fnames) {
    if ($name =~ m/^err:/) {
      last;
    }
    else {
    print "$name\n";
      shift(@fnames);
    }
  }

  #Get the error message
  ($heading, $errMsg) = split(/:/, $fnames[0]);
  $errMsg =~ s/^ //g;		#Trim leading space
  $errMsg =~ s/ $//g;		#Trim trailing space

  if ($errMsg =~ /no results/) {
    print qq|<title>No Match Found</title>\n|;
    print qq|</head> <body>\n|;
    print qq|<h3>There was no match for the search you specified</h3>\n|;
    print qq|<h4>Pattern: $FORM{'pattern'}</h4>\n|;
  }
  elsif ($errMsg =~ /too common/) {
    print qq|<title>Search Word too Common</title>\n|;
    print qq|</head> <body>\n|;
    print qq|<h3>One of the words specified is too common.</h3>\n|;
    print qq|<h4>Please try to narrow your search.</h4>\n|;
    print qq|<h4>Pattern: $FORM{'pattern'}</h4>\n|;
  }
  elsif ($errMsg =~ /index/) {
    print qq|<title>Search Index Error</title>\n|;
    print qq|</head> <body>\n|;
    print qq|<h3>There is a problem with the search index.<h3>\n|;
    print qq|<h4>Please notify the Web Master.<h4>\n|;
  }
  else {
    print qq|<title>Unknown Error</title>\n|;
    print qq|</head> <body>\n|;
    print qq|<h3>The following error was encountered when trying to perform the search.<h3>\n|; 
    print qq|<h4>Please notify the Web Master.</h4>\n|;
    print qq|<h5>Error: $errMsg</h5>\n|;
    print qq|<h5>Search Pattern:</h5> $FORM{'pattern'}\n|;
  }

  print qq|<p>Use <strong>Back</strong> to specify a different query,|;
  print qq| </A> or return to \n|;
 
  &print_overview;
  
  &cgi_footer;
}

sub do_bad_return {
    &cgi_head;
    print "<title>Bad Result from Search Engine</title>\n" ; 
    print "</head>\n" ;
    print "<body>\n" ;

    print "<h3>An error occured when trying to perform the search you requested.</h3>\n";
    print "<h4>Please notify the Web Master.</h4>\n";
    print "<h5>Search Pattern: $FORM{'pattern'}</h5>\n";

    print "<h5>The following was returned: </h5><PRE>\n";
    foreach (@fnames) {
	print "$_\n";
    }
    print "</PRE>";
    &cgi_footer;
}

    ######################
    # dih 951222
    sub print_overview {
       print "<a href=\"/sessions/$FORM{'session'}/overview.html\">";
       print "<img src=\"/pix/ccs-ico.gif\" align=bottom> CatoSource</a>\n";
    }
