#!/usr/local/bin/perl -w

$path = $0;
$path =~ s#/[^/]*$##;

require "$path/config.ph";

$lot=$MAX_ROWS*$THUMBS_ACCROSS;

# next line debug
open(STDERR,">>/tmp/perform_query$$") if ($VERBOSE);
print STDERR "THUMBS_ACCROSS=$THUMBS_ACCROSS\n";

printf("Content-type: text/html\n\n<TITLE>%s</TITLE>",URL_TITLE);

# printf("<FORM ACTION=\"http:perform_query\" METHOD=\"POST\">
#  $START_SEARCH_MESSAGE\n");


if ($ENV{'REQUEST_METHOD'} eq 'POST') {
      # Read in the desired number of bytes
      $request= "Z" x ($ENV{'CONTENT_LENGTH'}+4) ;
      read(STDIN, $request, $ENV{'CONTENT_LENGTH'});
} else {
       $request = $ENV{'QUERY_STRING'};
}

print "The Request to generate this page was<br>$request<br>" if $VERBOSE;
print "Set VERBOSE to 0 in config.ph to remove this message.<br><br>" if $VERBOSE;

@field = split(/&/, $request);

$combine_list_method = $ORING;   # Assume Oring unless told otherwise

$skip=0;
foreach $next_field (@field) {

    next if $next_field eq "ANDING=off";
    next if $next_field =~ /^NEXT/ ;
    next if $next_field =~ /^PREVIOUS/ ;
    next if $next_field =~ /^SUBMIT/i ;

    if ($next_field =~ /skiprecords/i)
     {($skip)= $next_field =~ /skiprecords=(.*)/i ; next; }

    if ( $next_field eq "ANDING=on" ) {
       $combine_list_method = $ANDING ;
       next;
    } else {
        ($field, $type, $search_for) = split(/%5C/, $next_field); 
        $patterns{$field} = "\L$search_for\E";          #Convert it to lowercase
        $types{$field} = $type;
    
        $patterns{$field} =~  s/=on$//;
        $patterns{$field} =~  tr/+/ /;
        $patterns{$field} =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
        $patterns{$field} =~ s/~!/ ~!/g;   # Stops people using subshells apparently

    }

print "F=$field<br>T=$type<br>S=$patterns{$field}<br><br>" if $VERBOSE;
}
    
$hits = 0;

open ( DBASE, "$DATABASE_FILENAME" ) || die "Unable to open $DATABASE_FILENAME";


$output_stuff=""; $thumb_stuff=""; $hold=0;
MAIN_LOOP:
while ( $record = <DBASE> ) {
#print STDERR "$record";
   chop $record;

   @the_record = split(/$FIELD_SEPARATOR/, $record);

   foreach $field ( keys %patterns ) {

      $the_record[$field-1] = "\L$the_record[$field-1]\E";

      # Check for substrings which are to be ANDED
      if ( $types{$field} == $ANDING ) {
          $gotcha = 1;

          AND_LOOP :
          foreach $item ( split(/\//,$patterns{$field}) ) {
 
              if ( $the_record[$field-1] !~ /$item/ ) {
                 $gotcha = 0;
                 last AND_LOOP;
                 }
          }
       }

       # Check for substring which are to be ORED
       if ( $types{$field} == $ORING ) {
          $gotcha = 0;

          OR_LOOP:
          foreach $item ( split(/\//,$patterns{$field}) ) {
#print STDERR ($field-1)," ",$the_record[$field-1]," ",$item,"\n";
 
              if ( $the_record[$field-1] =~ /$item/ ) {
                 $gotcha = 1;
                 last OR_LOOP;
                 }
          }
       }

       # Check for regular expression matching
       if ( $types{$field} == $REG_EXP ) {
          $gotcha = 0;

           if ( $the_record[$field-1] =~ /$patterns{$field}/ ) {
              $gotcha = 1;
           }
       }

       # Check for (year) ranges
       if ( $types{$field} == $YEARS ) {
          $gotcha = 0;

          ($lo, $hi) = split(/-/, $patterns{$field});

          $lo =~ s/(.*)BC(.*)/-$1$2/;
          $hi =~ s/(.*)BC(.*)/-$1$2/;

          $lo =~ s/AD//;
          $hi =~ s/AD//;


print "Is $the_record[$field-1]  in range $lo to $hi ? <br>" if ($VERBOSE);

          if ( $the_record[$field-1] ne undef && $the_record[$field-1] >= $lo && $the_record[$field-1] <= $hi ) {
                 $gotcha = 1;
          }
       }

       # Check for century ranges
       if ( $types{$field} == $CENTURIES ) {
          $gotcha = 0;

          ($lo, $hi) = split(/-/, $patterns{$field});

          $lo =~ s/(.*)BC(.*)/-$1$2/;
          $hi =~ s/(.*)BC(.*)/-$1$2/;

          $lo =~ s/AD//;
          $hi =~ s/AD//;

          $record_century = $the_record[$field-1];
          $record_century =~ s/(.*)BC(.*)/-$1$2/;
          $record_century =~ s/AD//;


print "Is $record_century  in range $lo to $hi ? <br>" if ($VERBOSE);

          if ( $record_century ne undef && $record_century >= $lo && $record_century <= $hi ) {
                 $gotcha = 1;
          }
       }



   next  MAIN_LOOP if !$gotcha && $combine_list_method == $ANDING;

   last if $gotcha && $combine_list_method == $ORING


   }
   $od = $OUTPUT_FORMAT;
   $od =~ s/FIELD\[([0-9]*)]/$the_record[$1-1]/eg;
   $od =~ s:AUTODIR\[([0-9]*)]:sprintf("%04d",$the_record[$1-1]/100):eg;
   $thd = $THUMB_FORMAT;
   $thd =~ s/FIELD\[([0-9]*)]/$the_record[$1-1]/eg;
   $thd =~ s:AUTODIR\[([0-9]*)]:sprintf("%04d",$the_record[$1-1]/100):eg;

#   print "$od" if $gotcha; # old code
#   $hits++ if $gotcha;

# cache until enough to go accross page DJB
   if ($gotcha)
    {if ($hits>=$skip && $hits<$skip+$lot)
      {$output_stuff .= $od; $thumb_stuff.= $thd;
       $hold++;
       (print($thumb_stuff,"<BR>",$output_stuff), $hold=0, $output_stuff="", $thumb_stuff="")
         if ($hold>=$THUMBS_ACCROSS);
      }
     $hits++;
    }

}
print($thumb_stuff,"<BR>",$output_stuff)
  if ($hold>0 && $hits<=$skip+$lot) ;

print("Total matching records $hits.<br>\n");
if ($hits>$lot)
 {$last=$skip+$lot;
  $last=$hits if ($last>$hits);
  $shown=$lot;
  $shown=$hits-$skip if ($shown>$hits-$skip);
  print("Only $shown are shown. (",$skip+1," to ",$last,")<BR>\n");
  if ($skip>0)
   {print(
      "<FORM ACTION=\"http://rubens.anu.edu.au/cgi-bin/michael4/perform_query.pl\" ".
      "METHOD=\"POST\">\n");
    @field = split(/&/, $request);
    foreach $next_field (@field)
     {next if $next_field =~ /^NEXT/ ;
      next if $next_field =~ /^PREVIOUS/ ;
      next if $next_field =~ /^SUBMIT/i ;
      ($name,$value)=split(/=/,$next_field);
  
      $name =~  tr/+/ /;
      $name =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
      $value =~  s/=on$//;
      $value =~  tr/+/ /;
      $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
  
      print("<INPUT TYPE=\"hidden\" NAME=\"$name\" VALUE=\"$value\">\n");
     }
    printf("<INPUT TYPE=\"hidden\" NAME=\"skiprecords\" VALUE=\"%d\">\n",$skip-$lot);
    print("<INPUT TYPE=\"submit\" NAME=\"PREVIOUS_$lot\" VALUE=\"PREVIOUS_$lot\">\n");
    print("</FORM>\n");
   }
  if ($skip+$lot<$hits)
   {print(
      "<FORM ACTION=\"http://rubens.anu.edu.au/cgi-bin/michael4/perform_query.pl\" ".
      "METHOD=\"POST\">\n");
    @field = split(/&/, $request);
    foreach $next_field (@field)
     {next if $next_field =~ /^NEXT/ ;
      next if $next_field =~ /^PREVIOUS/ ;
      next if $next_field =~ /^SUBMIT/i ;
      ($name,$value)=split(/=/,$next_field);
  
      $name =~  tr/+/ /;
      $name =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
      $value =~  s/=on$//;
      $value =~  tr/+/ /;
      $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
  
      print("<INPUT TYPE=\"hidden\" NAME=\"$name\" VALUE=\"$value\">\n");
     }
    printf("<INPUT TYPE=\"hidden\" NAME=\"skiprecords\" VALUE=\"%d\">\n",$skip+$lot);
    print("<INPUT TYPE=\"submit\" NAME=\"NEXT_$lot\" VALUE=\"NEXT_$lot\">\n");
    print("</FORM><BR>\n");
   }
 }
print("(None at all, sorry.)<br>\n")
  if ($hits <= 0);
print("<hr>\n");

print("$END_SEARCH_MESSAGE");


_END__
