#!/usr/local/bin/perl

&PrintHeader;
&ReadParse;

$mailprog = '/usr/lib/sendmail';

@badtitles = ('of', 'to' , 'it');
@badcombtitles = ( 'inthe' , 'andthe' , 'ofthe' );
@badauthors = ( 'and' );
@badcombauthors = (',eds' , '=,ed');
@badpublishers = ('and' , 'co', 'the' );
@badcombpublishers = (  'uof' );

$mailout = 0;
$hiddenquery = $in{'hiddenval'};

if ( length ($hiddenquery) >0 ) {
  ($field, $hiddenval) = split(/\=/,$hiddenquery, 2 );
  $hiddenval =~ s/\+/ /g;
  
  ($bool,$keywords) = split(/\//,$hiddenval, 2 );  
  $key =  $bool;
  $mailout = 1;
}
else { 
  $field = $in{'subject'};
  $bool = $in{'boolean'};
  $key = $in{'searchbox'};
  $keywords = $in{'keyword'};
}

$libfile = '/home/arts/english/iemls/mqlibrary/mq.library';

open(lib,$libfile) || die " Can't open library file \n ";

# set the search field's relative position in the database
# and check the format of the input fields

$inputfail = 0;

if  ($field eq 'Keyword') 
{
  $keywords =~ tr/a-z/A-Z/;
  ($blankword = $keywords ) =~  tr/ //d;
  if ( $blankword eq '' ){
    $inputfail = 1;
    $reason = " Enter a keyword and try again <br> \n";
  } 
}    
else
{
  $key =~ s/ +/ /g;
  ($blankword = $key ) =~  tr/ //d; 
  if ( length($blankword) < 2 ){
    $inputfail = 1;
    $reason = " Enter a more specific search value and try again <br> \n";    
  }
  else{
    if ($field eq 'Author')            # 1 author in 2
    {  $fieldnumber = 1;
       $inputfail = &CheckBadWords( $blankword , *badauthors , *badcombauthors);
       $reason = "Enter a more explicit author \n <br>";
       $key =~ tr/ //d;
       @inputnames = split (/,/,$key);
       @inputnames[0] =~  tr/A-Z/a-z/;
       $totalnames = $#inputnames + 1;
    }
    elsif ($field eq 'Title')          # 2 title in 3
    {  $fieldnumber = 2;
       $inputfail = &CheckBadWords( $blankword , *badtitles , *badcombtitles);
       $reason = "Enter a more explicit title \n <br>";
    }
    elsif  ($field eq 'Publisher')     # 3 publisher in 5   
    {  $fieldnumber = 4;
       $inputfail = &CheckBadWords( $blankword , *badtitles , *badcombpublishers );
       $reason = "Enter a more explicit publisher \n <br>";
    }
    elsif  ($field eq 'Year')          # 4 year in 6   
      {$fieldnumber = 5;
                                       # add in the number test late
      }
  }
}

if ($inputfail > 0){
  print " Search Failure $inputfail <br> \n ";
  print $reason;

}
else {
  if ($field eq 'Keyword' )        # keyword search
  {
    @searchwords = split( /\//, $keywords );
    $words = $#searchwords + 1;
     
    for ( $i = 0 ; $i < $words ; $i++ ){
      @searchwords[$i] = "/" . @searchwords[$i] . "/";
    }
    
    while(<lib>){
      @allfields = split(/\t/);
      $keyfield = pop allfields;
      chop $keyfield;
    
      if (&KEYSEARCH ( $bool, $words, $keyfield, *searchwords )){
        push (@output,  join("\t", @allfields[2],@allfields[1],
                @allfields[4],@allfields[5],"\n"));
      }
    }
  }
  else                              # all other field search
  {
     if ($field eq 'Author') {
       if ($totalnames == 1) {
         while(<lib>){
           @allfields = split(/\t/); 
           $keyfield = @allfields[$fieldnumber];
           $keyfield =~  tr/A-Z/a-z/;
           @names = split (/,/,$keyfield); 
           if (@names[0] eq @inputnames[0]) {
             push (@output, join("\t", @allfields[2],@allfields[1],
                       @allfields[4],@allfields[5],"\n"));
           }
        }
       }
       else {
         $namelength = length(@inputnames[1]);
         $packval = "a$namelength";
         @inputnames[1] =~  tr/A-Z/a-z/;
         while(<lib>){
            @allfields = split(/\t/); 
            $keyfield = @allfields[$fieldnumber];
            $keyfield =~  tr/A-Z/a-z/;
            $keyfield =~  tr/ //d;
            @names = split (/,/,$keyfield); 

            if (@names[0] eq @inputnames[0] && 
                   pack($packval,@names[1]) eq @inputnames[1]) 
            {
              push (@output, join("\t", @allfields[2],@allfields[1],
                         @allfields[4],@allfields[5],"\n"));}
         }
       }
    }
    else {
      ($otherkey=$key) =~ tr/A-Z/a-z/;
      while(<lib>){
        @allfields = split(/\t/); 
        $keyfield = @allfields[$fieldnumber];
        $keyfield =~  tr/A-Z/a-z/;
        if (index ($keyfield, $otherkey) >= 0 ){
          push (@output, join("\t", @allfields[2],@allfields[1],
                   @allfields[4],@allfields[5],"\n"));
        }
      }
    }
  }

  $found =  $#output + 1;
  $found == 1 ? {$ess = ''}:{ $ess ='s'};
  
  if ( $mailout == 1 ) {
    &MailList( $in{'username'}, $in{'realname'} ,$found, *output );
  }  
  else {
    MailForm( $found ,$field, $bool, $key, $keywords); 
    print "<br> $found title$ess found <br>  \n ";
    PrintList( *output ); 
  }
}
print "\n</body></html>\n";

########################
#subroutines
########################

sub KEYSEARCH {
  local( $and ,$count, $string, *words) = @_;
  $result = 0;

  if ( $and eq 'and' ) {
    foreach $elem ( @words ) {
      if (index ($string, $elem) >= 0 ){           
	$result++;             
      }
    }
    ($result == $count) ? ($result = 1) : ($result = 0 ) ;
  }
  else {
    foreach $elem ( @words ) {
      if (index ($string, $elem) >= 0 ){           
	$result++;             
      }
    }
    ($result > 0) ? ($result = 1) : ($result = 0 ) ;
  }
  return $result;
}     

########################

sub ReadParse {
  local (*in) = @_ if @_;
  local ($i, $key, $val);

  # Read in text
  if (&MethGet) {
    $in = $ENV{'QUERY_STRING'};
  } elsif ($ENV{'REQUEST_METHOD'} eq "POST") {
    read(STDIN,$in,$ENV{'CONTENT_LENGTH'});
  }

  @in = split(/&/,$in);
  $count = 0;
  foreach $i (0 .. $#in) {
    # Convert plus's to spaces
    $in[$i] =~ s/\+/ /g;

    # Split into key and value.  
    ($key, $val) = split(/=/,$in[$i],2); # splits on the first =.

    # Convert %XX from hex numbers to alphanumeric
    $key =~ s/%(..)/pack("c",hex($1))/ge;
    $val =~ s/%(..)/pack("c",hex($1))/ge;

    # Associate key and value
    if ($key eq 'keyword' ) {
        $in{$key} .= $val . "/"; 
    }
    else {
        $in{$key} .= $val;
    }
  }
  $count; 
}

########################
sub PrintHeader {

  print "Content-type: text/html\n\n";
  print "<title>Book list</title>";
  print "<Body><H1>Book List</H1>\n";

  print "<A HREF=\"http://unixg.ubc.ca:7001/0/e-sources/emls/emlshome.html\">";
  print "<IMG SRC=\"http://home/arts/english/emls/emlsname.gif\" Width=557 Height=37 Alt=\"\"></A>";

  print "<H2><I>Early Modern Literary Studies</I>: Library Search</H2>\n";
  print "<hr> \n"; 

}
#######################
# MethGet
# Return true if this cgi call was using the GET request, false otherwise

sub MethGet {
  return ($ENV{'REQUEST_METHOD'} eq "GET");
}

#######################
sub  CheckBadWords {
  local ( $inword , *list , *combolist) = @_ ;
  local ( $retval )= 0;
  local ( $badword, $badcomboword ); 
  foreach $badword ( @list ){
    if ( $inword eq $badword )
    {  $retval =1; }
  }
  foreach  $badcomboword ( @combolist ){
    if (index ( $badcomboword, $inword ) >= 0 )
    {  $retval = 1; } 
  }   
  $retval;
}

########################
sub MailForm {
  local ( $total , $keyfield, $boolval, $keyvalue, $words ) = @_;
  local (@vals, $elem);

  if ( $total > 0 ) { 
    print " Enter you name and e-mail address if you desire a list of the results <br>\n";
    print "<form method=POST action=\"http://edziza.arts.ubc.ca/cgi-bin/dbase.pl\"> \n";
    print "Your Name:<input type=text name=realname size=30><br>\n";
    print "E-Mail: <input type=text name=username size=40><br>\n";
    print "<br> <input type=submit Value= Mail> * <input type=reset> \n"; 
    print "<HR>\n";
  }
  print "  Search on ";

  if  ( $keyfield eq 'Keyword' )
    {@vals = split(/\//,$words);
     print " $keyfield <b>$boolval</b> of <b> @vals</b>  \n";
     $hidden = "$keyfield=$boolval";
     foreach $elem ( @vals ) {
       $hidden = $hidden . "/$elem";
      }
     } 
  else
  {  print " <b>$keyfield = $keyvalue</b>\n";
     $keyvalue =~ tr/ /+/;
     $hidden = $keyfield. "=" . $keyvalue; 
  }

  print "<INPUT TYPE=hidden NAME=hiddenval VALUE=$hidden> \n";
  print "</form>\n";

}


########################
sub MailList {

  local ( $user, $realname ,$references, *mailoutput ) = @_;
  local ( $ref  );

  if (  $user  ){

    open (MAIL, "|$mailprog $user") || die "Can't open $mailprog!\n";
    print "The results have been sent to $realname at $user \n";

    print MAIL "Reply-to: $user , $realname\n";
    print MAIL "From: EMLS\@arts.ubc.ca \n";
    print MAIL "Subject: IEMLS list \n\n";
    print MAIL "------------------------------------------------------\n";

    foreach $ref ( @mailoutput )
    {
      ($title, $author,$publisher, $year, @searchwords) = split(/\t/, $ref);
      print MAIL "AUTHOR: $author \nTITLE: $title \nPUBLISHER:$publisher, YEAR:$year\n\n";
    }

  close(MAIL);
  }

}


########################
sub PrintList {

  local( *listoutput ) = @_;
   
  foreach $fields ( @listoutput )
  {
    ($title, $author,$publisher, $year, @searchwords) = split(/\t/, $fields);
    print " <BR> <b>$author</b>, <i>$title</i>, $publisher, $year <br>\n";
  }

}