#!/usr/bin/perl
print "Content-type: text/html\n\n";
use CGI::Carp qw/fatalsToBrowser/;
$LINE_COUNT = 10;
$RESULTS = "";

use lib "../lib";
require HTML::HeadParser1;
require("cgi-lib.pl");
require("oma-lib.pl");
&ReadParse(*FORM);

$A = $FORM{"author"};
$T = $FORM{"title"};
$K = $FORM{"keywords"};

foreach $holder (keys(%FORM)){
#	print $holder,"=$FORM{$holder}","<br>";
}

if ($FORM{"do"} ne "search"){
	print_html("tmpl_otsi.htm");
	exit;
}else {
	my $files = [];
	get_filelist($files,".");
	$results = get_results($files, {author=>$FORM{"author"}, title=>$FORM{"title"}, keywords=>$FORM{"keywords"}} );
	
	foreach $result (@$results){
		$RESULTS .= '<a href="'.$result->{file}.'">'.$result->{title}.", ". $result->{author} . '</a><br><br>';
	}
	print_html("tmpl_otsi.htm");
}



exit;


# returns array of hashrefs;
sub get_results (){
	my $files = shift;	
	my $criteria = shift;
	my $struct = [];

	my $t = uc $criteria->{title};
	my $a = uc $criteria->{author};
	my $k = uc $criteria->{keywords};
	
	foreach $file (@$files){
		my $h_ref = get_head_inf($file);
		$h_ref->{file}= $file;
		
		my $c = 0;
		
#		print $h_ref->{title},"-",$t,"<br>";
#		print $h_ref->{author},"-",$a,"<br>";
#		print $h_ref->{keywords},"-",$k,"<br>";
		
		$c ++ if (index(uc $h_ref->{title},$t) != -1);
		$c ++ if (index(uc $h_ref->{author},$a) != -1);
		$c ++ if (index(uc $h_ref->{keywords},$k) != -1);
		push @$struct,$h_ref if ($c == 3);
	
	}
	return $struct;
}

# returns recursive list of files of dir provided
sub get_filelist {
	my $files = shift;
	my $dir = shift;
	my $dn;
	
	local *BIN;
	opendir(BIN, $dir) or die "Can't open $dir: $!";
	while( defined ($file = readdir BIN) ) {
		next if ($file eq "." or $file eq "..");
		next if (($dir eq "." and -T "$dir/$file") or $file eq "index.htm");
		push @$files, "$dir/$file" if -T "$dir/$file";
		get_filelist($files, "$dir/$file") if -d "$dir/$file";
	}
	closedir(BIN);
}

sub get_head_inf {
	my $path = shift;	
	my $text;
	open IN, "$path" or die "can't open $path";
	$. = 0;
	while ($. != $LINE_COUNT || eof){
		$line = <IN>;
		$text .= $line;
	}
	close IN;
	
	$p = HTML::HeadParser1->new;
	$p->parse($text);
	
	my $keywords = $p->header('keywords')?$p->header('keywords'):"";
	return {title=>$p->header('title'),
					author => $p->header('author') ,
					keywords => $keywords}
}

