#!/usr/bin/perl

# This script produces pdfs
# of search results.
#
# copyright (c) Hans-Michael Muller, Pasadena, California, 2002-2004
#

use strict;
use CGI;
use PDF::Create;

### globals
#

# handle to this CGI and own address
my $query = new CGI;
my $absmyself = $query->url(absolute=>1);

# directories of importance

my $databaseroot = "/var/www/html/text/tdb/";

my $minx = 0;
my $maxx = 612;
my $miny = 0;
my $maxy = 792;

my $pagelimit = 200;

my $fsbase = int($maxx/100); # font base size

my $tminx = 7*$fsbase;
my $tmaxx = $maxx - 7*$fsbase;
my $tminy = 9*$fsbase;
my $tmaxy = $maxy - 12*$fsbase;

# cookies
my %generalsettings = $query->cookie('generalsettings'); # general settings
my %displayoptions; # display options
if ($query->cookie('displayoptions')) {
    %displayoptions = $query->cookie('displayoptions');
} else {
    $displayoptions{'Source Type'} = 1;
    $displayoptions{Title} = 1;
    $displayoptions{Abstract} = 1;
    $displayoptions{Author} = 1;
    $displayoptions{Journal} = 1;
    $displayoptions{Year} = 1;
    $displayoptions{Citation} = 1;
    $displayoptions{'Number of matches'} = 1;
    $displayoptions{Select} = 1;
}
my %displayvalues; # display values
if ($query->cookie('displayvalues')) {
    %displayvalues = $query->cookie('displayvalues');
} else {
    $displayvalues{SentencesPerMatch} = 10;
}
# other globals of interest
my %targetdirectories = (Author => 'aut/', Title => 'tit/', 
			 Abstract => 'abs/', Paper => 'art/');

my %labels = ReadElements("/var/www/html/text/textpresso.dtd");

$|=1;

#
### end of globals


PrintHeader($query);
	    
### output goes here
#
	    
my $filename = $databaseroot . "tmp/file" . $query->param('id');

if (!-e "$filename\.pdf") {

    open (IN, "$filename");
    my $categoryline = <IN>;
    chomp($categoryline);
    my $keywordline = <IN>;
    chomp ($keywordline);

    my @aux = split ("\,", $categoryline);
    my @categories;
    my @catcomments;
    foreach my $element (@aux) {
	(my $cat, my $comment) = split(/\#/, $element);
	do {
	    push @categories, $cat;
	    push @catcomments, $comment;
	} unless ($element eq "");
    }
    @aux = split ("\,", $keywordline);
    my @keywords;
    my @keycomments;
    foreach my $element (@aux) {
	(my $key, my $comment) = split(/\#/, $element);
	push @keywords, $key;
	push @keycomments, $comment;
    }
    
    my $limitreached = 0;

####
#
# open PDF document
#

    my $pdf = new PDF::Create('filename' => $filename . '.pdf',
			      'Version'  => 1.2,
			      'PageMode' => 'UseOutlines',
			      'Author'   => 'Textpresso',
			      'Creator' => 'Textpresso',
			      'Title'    => 'Requested Results from Textpresso',
			      );

    my $root = $pdf->new_page('MediaBox'  => [ $minx, $miny, $maxx, $maxy ]);

#
# 
#
####

####
#
# start with page 1; page which inherits its attributes from $root
#

    my $curpage = $root->new_page;
    my $curnumber = 1;
    my $curypos = $tmaxy;
    ProduceHeadandFoot($pdf, $fsbase, $minx, $maxx, 
		       $miny, $maxy, $curpage, $curnumber);

#
#
#
####

    my $boldtext = "Your Query:";
    my $normaltext;
    $pdf->new_outline('Title' => 'Query', 'Destination' => $curpage);
    
    ($curpage, $curnumber, $curypos) = FormatText ($root, $pdf, $curpage, 
						   $curnumber, $curypos, $boldtext, 
						   $normaltext, $fsbase, 
						   $tminx, $tmaxx, $tminy, $tmaxy,
						   $minx, $maxx, $miny, $maxy);
    ($curpage, $curnumber, $curypos) = NewLine ($root, $pdf, $curpage, 
						$curnumber, $curypos, $fsbase, 
						$tminy, $tmaxy,
						$minx, $maxx, $miny, $maxy);
    
    $boldtext = "";
    $normaltext = "";
    if (@categories) {
	$normaltext .= "Categories ";
	for (my $i = 0; $i < @categories; $i++) {
	    $normaltext .= " + ";
	    $normaltext .= $labels{$categories[$i]} . " ";
	    $normaltext .= " (" . $catcomments[$i] . " ) " if ($catcomments[$i]);
	}
    }
    
    if (@keywords) {
	$normaltext .= "- Keywords ";
	for (my $i = 0; $i < @keywords; $i++) {
	    $normaltext .= " + ";
	    $normaltext .= $keywords[$i] . " ";
	    $normaltext .= " (" . $keycomments[$i] . " ) " if ($keycomments[$i]);
	}
    }
    
    
    ($curpage, $curnumber, $curypos) = FormatText ($root, $pdf, $curpage, 
						   $curnumber, $curypos, $boldtext, 
						   $normaltext, $fsbase, 
						   $tminx, $tmaxx, $tminy, $tmaxy,
						   $minx, $maxx, $miny, $maxy);
    ($curpage, $curnumber, $curypos) = NewLine ($root, $pdf, $curpage, 
						$curnumber, $curypos, $fsbase, 
						$tminy, $tmaxy,
						$minx, $maxx, $miny, $maxy);
    
    my %displaylist = ();
    while (my $line = <IN>) {
	chomp ($line);
	my @items = split (/\,/, $line);
	my $target = shift(@items);
	my $key = shift(@items);
	while (my $sentence = shift(@items)) {
	    $displaylist{$target}{$key}{$sentence} = 1;
	}
    }
    close (IN);

#
###

### second part of output goes here
#

    $boldtext = "R E S U L T S";
    $normaltext = "";
    $pdf->new_outline('Title' => 'Start of Results', 'Destination' => $curpage);
    
    ($curpage, $curnumber, $curypos) = FormatText ($root, $pdf, $curpage, 
						   $curnumber, $curypos, $boldtext, 
						   $normaltext, $fsbase, 
						   $tminx, $tmaxx, $tminy, $tmaxy,
						   $minx, $maxx, $miny, $maxy);
    ($curpage, $curnumber, $curypos) = NewLine ($root, $pdf, $curpage, 
						$curnumber, $curypos, $fsbase, 
						$tminy, $tmaxy,
						$minx, $maxx, $miny, $maxy);
    ($curpage, $curnumber, $curypos) = NewLine ($root, $pdf, $curpage, 
						$curnumber, $curypos, $fsbase, 
						$tminy, $tmaxy,
						$minx, $maxx, $miny, $maxy);
    
    my %sortscorelist = SortedList(\%displaylist);
    print $query->font({-face => 'verdana, arial, helvetica', -color => 'green'}, 'Processed..');
    foreach my $score (sort numerically keys % sortscorelist) {
	foreach my $key (sort keys %{$sortscorelist{$score}}) {
	    if ($curnumber < $pagelimit) {
		$boldtext = "ID:";
		$normaltext = $key;
		$pdf->new_outline('Title' => $key, 'Destination' => $curpage);
		($curpage, $curnumber, $curypos) = FormatText ($root, $pdf, $curpage, 
							       $curnumber, $curypos, $boldtext, 
							       $normaltext, $fsbase, 
							       $tminx, $tmaxx, $tminy, $tmaxy,
							       $minx, $maxx, $miny, $maxy);	
		if ($displayoptions{'Source Type'}) {
		    $boldtext = "Publication Type:";
		    my $content = GetContents("$databaseroot/typ/$key");
		    chomp($content);
		    $normaltext = "\L$content\E";
		    if ($normaltext) {
			($curpage, $curnumber, $curypos) = FormatText ($root, $pdf, $curpage, 
								       $curnumber, $curypos, $boldtext, 
								       $normaltext, $fsbase, 
								       $tminx, $tmaxx, $tminy, $tmaxy,
								       $minx, $maxx, $miny, $maxy);	
		    }
		}
		if ($displayoptions{Title}) {
		    $boldtext = "Title:";
		    $normaltext = GetContents("$databaseroot/tit/xml/$key");
		    $normaltext =~ s/\n//g;
		    $normaltext =~ s/<.+?>//g;
		    $normaltext =~ s/<\/.+?>//g;
		    $normaltext =~ s/\s\,\s/\, /g;
		    $normaltext =~ s/\s\;\s/\; /g;
		    $normaltext =~ s/\s\.\s/\./g;
		    if ($normaltext) {
			($curpage, $curnumber, $curypos) = FormatText ($root, $pdf, $curpage, 
								       $curnumber, $curypos, $boldtext, 
								       $normaltext, $fsbase, 
								       $tminx, $tmaxx, $tminy, $tmaxy,
								       $minx, $maxx, $miny, $maxy);
		    }
		}
		if ($displayoptions{Author}) {
		    $boldtext = "Author:";
		    $normaltext = GetContents("$databaseroot/aut/$key");
		    chomp($normaltext);
		    $normaltext =~ s/\n/\, /g;
		    if ($normaltext) {
			($curpage, $curnumber, $curypos) = FormatText ($root, $pdf, $curpage, 
								       $curnumber, $curypos, $boldtext, 
								       $normaltext, $fsbase, 
								       $tminx, $tmaxx, $tminy, $tmaxy,
								       $minx, $maxx, $miny, $maxy);
		    }    
		}
		if ($displayoptions{Journal}) {
		    $boldtext = "Journal:";
		    $normaltext = GetContents("$databaseroot/jou/$key");
		    chomp($normaltext);
		    if ($normaltext) {
			($curpage, $curnumber, $curypos) = FormatText ($root, $pdf, $curpage, 
								       $curnumber, $curypos, $boldtext, 
								       $normaltext, $fsbase, 
								       $tminx, $tmaxx, $tminy, $tmaxy,
								       $minx, $maxx, $miny, $maxy);
		    }    
		}
		if ($displayoptions{Year}) {
		    $boldtext = "Year:";
		    $normaltext = GetContents("$databaseroot/yea/$key");
		    chomp($normaltext);
		    if ($normaltext) {
			($curpage, $curnumber, $curypos) = FormatText ($root, $pdf, $curpage, 
								       $curnumber, $curypos, $boldtext, 
								       $normaltext, $fsbase, 
								       $tminx, $tmaxx, $tminy, $tmaxy,
								       $minx, $maxx, $miny, $maxy);
		    }    
		}
		if ($displayoptions{Citation}) {
		    $boldtext = "Citation:";
		    $normaltext = GetContents("$databaseroot/cit/$key");
		    chomp($normaltext);
		    $normaltext =~ s/P\:\s+(\d+)\s+(\d+)/Pages $1-$2, /g;
		    $normaltext =~ s/V\:/Vol\./g;
		    $normaltext =~ s/\n//g;
		    if ($normaltext) {
			($curpage, $curnumber, $curypos) = FormatText ($root, $pdf, $curpage, 
								       $curnumber, $curypos, $boldtext, 
								       $normaltext, $fsbase, 
								       $tminx, $tmaxx, $tminy, $tmaxy,
								       $minx, $maxx, $miny, $maxy);
		    }    
		}
		if ($displayoptions{Abstract}) {
		    $boldtext = "Abstract:";
		    $normaltext= GetContents("$databaseroot/abs/xml/$key");
		    $normaltext =~ s/\n//g;
		    $normaltext =~ s/<.+?>//g;
		    $normaltext =~ s/<\/.+?>//g;
		    $normaltext =~ s/\s\,\s/\, /g;
		    $normaltext =~ s/\s\;\s/\; /g;
		    $normaltext =~ s/\s\.\s/\./g;
		    if ($normaltext) {
			($curpage, $curnumber, $curypos) = FormatText ($root, $pdf, $curpage, 
								       $curnumber, $curypos, $boldtext, 
								       $normaltext, $fsbase, 
								       $tminx, $tmaxx, $tminy, $tmaxy,
								       $minx, $maxx, $miny, $maxy);
		    }    	    
		}
		if ($displayoptions{'Number of matches'}) {
		    $boldtext = "Number of Matches:";
		    $normaltext = $score;
		    if ($normaltext) {
			($curpage, $curnumber, $curypos) = FormatText ($root, $pdf, $curpage, 
								       $curnumber, $curypos, $boldtext, 
								       $normaltext, $fsbase, 
								       $tminx, $tmaxx, $tminy, $tmaxy,
								       $minx, $maxx, $miny, $maxy);
		    }    	        
		}
		
		if ($displayoptions{Select}) {
		    $boldtext = "Matches:";
		    $normaltext = "";
		    ($curpage, $curnumber, $curypos) = FormatText ($root, $pdf, $curpage,
								   $curnumber, $curypos, $boldtext,
								   $normaltext, $fsbase,
								   $tminx, $tmaxx, $tminy, $tmaxy,
								   $minx, $maxx, $miny, $maxy);
		    ($curpage, $curnumber, $curypos) = NewLine ($root, $pdf, $curpage,
								$curnumber, $curypos, $fsbase,
								$tminy, $tmaxy,
								$minx, $maxx, $miny, $maxy);
		    foreach my $target (keys % displaylist) {
			next unless $displaylist{$target}{$key};
			foreach my $centersentence (sort sortsen keys % { $displaylist{$target}{$key} }) {
			    my @output = GetSentences ($query, $target, $key, $centersentence, $displayvalues{SentencesPerMatch},
						       \%targetdirectories, $databaseroot);
			    $boldtext = shift(@output);
			    $normaltext = join(/ /, @output);
			    $normaltext =~ s/\n//g;
			    $normaltext =~ s/<.+?>//g;
			    $normaltext =~ s/<\/.+?>//g;
			    $normaltext =~ s/\s\,\s/\, /g;
			    $normaltext =~ s/\s\;\s/\; /g;
			    $normaltext =~ s/\s\.\s/\./g;
			    ($curpage, $curnumber, $curypos) = FormatText ($root, $pdf, $curpage,
									   $curnumber, $curypos, $boldtext,
									   $normaltext, $fsbase,
									   $tminx, $tmaxx, $tminy, $tmaxy,
									   $minx, $maxx, $miny, $maxy);
			}
		    }
		}
		($curpage, $curnumber, $curypos) = NewLine ($root, $pdf, $curpage, 
							    $curnumber, $curypos, $fsbase, 
							    $tminy, $tmaxy,
							    $minx, $maxx, $miny, $maxy);	
	    } else {
		$limitreached = 1;
		}
	    last if ($limitreached);
	}
	last if ($limitreached);
    }
    $pdf->close;
    print $query->p;
    if ($limitreached) {
	print $query->font({-face => 'verdana, arial, helvetica', -color => 'red'}, 'The requested document has exceeded ');
	print $query->font({-face => 'verdana, arial, helvetica', -color => 'red'}, 'the limit of ',$pagelimit, ' pages, and the generated PDF document may not be ');
	print $query->font({-face => 'verdana, arial, helvetica', -color => 'red'}, 'complete. Please refine your query further, ');
	print $query->font({-face => 'verdana, arial, helvetica', -color => 'red'}, 'or limit the display options or number of ');
	print $query->font({-face => 'verdana, arial, helvetica', -color => 'red'}, 'sentences around a match in the \'customization\' page. ');
	print $query->p;
    } else {
	print $query->font({-face => 'verdana, arial, helvetica'}, 'The requested document contains ');
	print $query->font({-face => 'verdana, arial, helvetica'}, $curnumber);
	print $query->font({-face => 'verdana, arial, helvetica'}, ' page');
	print $query->font({-face => 'verdana, arial, helvetica'}, 's') if ($curnumber > 1);
	print $query->font({-face => 'verdana, arial, helvetica'}, '.');
	print $query->p;
    }
}

print $query->font({-face => 'verdana, arial, helvetica'}, 'Click on the icon to download PDF: ');
my $address = "/text/tdb/tmp/file" . $query->param('id') . ".pdf";
print $query->a({href => $address, target => "_blank"},
		$query->img({-src => "/text/gif/pdf.gif", -border => 0, -align => 'middle', -alt => 'PDF'}));

#
###

#### end form here
##
#
#print $query->hidden(-name => 'id', -default => $query->param('id'));
#print $query->hidden(-name => 'totalpages', -default => $totalpages);
#print $query->end_form;
#
##
####

#### close html
##
#

print $query->end_html;

#
##
###

sub sortsen {

    $a =~ s/s//;
    $b =~ s/s//;
    $a <=> $b;
}

sub GetSentences {

    my $query = shift;
    my $target = shift;
    my $key = shift;
    my $sentence = shift;
    my $halfwidth = shift;
    my $pTargetdirectory = shift;
    my $databaseroot = shift;

    (my $center = $sentence) =~ s/s//;
    my $start = $center - $halfwidth;
    my $end = $center + $halfwidth;
    $start = ($start > 0) ? $start : 1;

    my @output = ();
    push @output, "Sentences $start to $end: ";

    for (my $i = $start; $i < $end + 1; $i++) {
	my $filename = $databaseroot . $$pTargetdirectory{$target} . "xml/" . $key;
	my $content = GetContentsOfSentence($filename, $i);
	push @output, $content;
    }
    return @output;

} # end GetSentences

sub PrintHeader { # begin PrintHeader
    
    my $query = shift;
    my @cookies = ();
    while (@_) { push @cookies, shift(@_)}
    
    print $query->header(-cookie=>[@cookies]);
    print $query->start_html(-title=>'Generate PDF Output', -author=>'Hans-Michael Muller',
			     -bgcolor => '#e6e6f6',
			     -text=>'#000000', -link=>'#662222', -vlink=>'#993333');
    print $query->br;
    print $query->font({-face => 'verdana, arial, helvetica', -size => '5'}, 'Generate Output in PDF Format');
    print $query->p;
    print $query->font({-face => 'verdana, arial, helvetica'}, 'Your research results are available for 72 hours. If you want to regenerate the PDF file without ');
    print $query->font({-face => 'verdana, arial, helvetica'}, 'submitting the query again, go to ');
    print $query->p;
    print $query->font({-face => 'verdana, arial, helvetica'}, $query->url);
    print $query->font({-face => 'verdana, arial, helvetica'}, '?id=');
    print $query->font({-face => 'verdana, arial, helvetica'}, $query->param('id'));
    print $query->p;
    print $query->font({-face => 'verdana, arial, helvetica'}, 'The PDF document contains all information ');
    print $query->font({-face => 'verdana, arial, helvetica'}, 'selected under \'Display Options\' ');
    print $query->font({-face => 'verdana, arial, helvetica'}, 'in the \'Customization\' page. ');
    print $query->font({-face => 'verdana, arial, helvetica'}, 'Go to that page ');
    print $query->font({-face => 'verdana, arial, helvetica'}, 'to change your options. ');
    print $query->font({-face => 'verdana, arial, helvetica'}, 'If a particular information is still not ');
    print $query->font({-face => 'verdana, arial, helvetica'}, 'displayed, it does not exist ');
    print $query->font({-face => 'verdana, arial, helvetica'}, 'for a given reference. ');

    print $query->p;
    
} # end PrintHeader

sub PrintBottom { # begin PrintBottom
    my $query = shift;
}   # end PrintBottom

sub ReadElements {

    my $dtdfile = shift;
    my %labels = ();
    $labels { "" } = "none"; # include empty tag for search
    open (DTDFILE, "$dtdfile") or die "Can't open DTD file $dtdfile.";   

    while (my $line = <DTDFILE>) {
	chomp ($line);
	if ($line =~ /<!ELEMENT\s+(\w+)\s\(\#PCDATA\)> <\!--\s((\w|\s)+)\s-->/) {
	    my $key = $1;
	    my $label = $2;
	    if (($key ne "sentence") && ($key ne "article")){  #because pattern above is more specific, this isn't really necessary
		 $labels { substr($key, 0, 2) } = $label;
	    }
	}
    }
    close (DTDFILE);
    return %labels;
}

sub GetContentsOfSentence {

    my $filename = shift;
    my $number = shift;
    open (IN,"$filename");
    while (my $line = <IN>) { 
	next unless ($line =~ /<sentence id=\'s$number\'>/);
	return $line;
    }
    close (IN);
    return "";
}

sub numerically { $b <=> $a }

sub SortedList {

    my $pSearchresults = shift;
    
    my %scorelist = ();
    foreach my $target (keys % {$pSearchresults}) {
	foreach my $key (keys % { $$pSearchresults{$target} }) {
	    foreach my $sentence (keys % { $$pSearchresults{$target}{$key} }) {
		$scorelist{$key} += $$pSearchresults{$target}{$key}{$sentence};
	    }
	}
    }
    
    my %sortscorelist = ();

    foreach my $key (keys % scorelist) {
	$sortscorelist{$scorelist{$key}}{$key} = 1;
    }    
    return %sortscorelist;

}

sub FormatText {

    my $root = shift;
    my $pdf = shift;
    my $curpage = shift;
    my $curnumber = shift;
    my $ypos = shift;
    my $boldtext = shift;
    my $normaltext = shift;
    my $fsbase = shift;
    my $tminx = shift;
    my $tmaxx = shift;
    my $tminy = shift;
    my $tmaxy = shift;
    my $minx = shift;
    my $maxx = shift;
    my $miny = shift;
    my $maxy = shift;

    my $boldfont = $pdf->font('Subtype'  => 'Type1',
			      'Encoding' => 'StandardEncoding',
			      'BaseFont' => 'Times-Bold');
    my $normalfont = $pdf->font('Subtype'  => 'Type1',
				'Encoding' => 'StandardEncoding',
				'BaseFont' => 'Times-Roman');
    my $fs = 2*$fsbase;

    my $xpos = $tminx;

    if ($boldtext) {
	(my $out = $boldtext) =~ s/\(/\\\(/g;
	$out =~ s/\)/\\\)/g;
	$curpage->stringl($boldfont, $fs, $xpos, $ypos, $out . " ");
	$xpos += $fs*$curpage->string_width($boldfont, $boldtext . " ");
    }
    my @aux = split (/\s/, $normaltext);
    my @words;
    for (my $i = 0; $i < @aux; $i++) { # watch out for words that are longer than a line
	my $lngth = $fs*$curpage->string_width($normalfont, $aux[$i]);
	if ($lngth > $tmaxx-$tminx) {
	    my $noofparts = int($lngth/($tmaxx-$tminx) + 1);
	    my $l = length($aux[$i]);
	    my $segmentlength = $l/$noofparts;
	    for (my $j = 0; $j < $noofparts; $j++) {
		my $part = substr($aux[$i], $j*$segmentlength, $segmentlength);
		push @words, $part;
	    }
	} else {
	    push @words, $aux[$i];
	}
    }
    while (@words) {
	my @line = ();
	my $testpos = $xpos;
	my $inc = 0;
	while (($testpos < $tmaxx) && (@words)) {
	    my $term = shift(@words) . " ";
	    if (!@words) { $term =~ s/ $// }
	    push @line, $term;
	    $inc = $fs*$curpage->string_width($normalfont, $term);
	    $testpos += $inc;
	}
	my $diff = 0;
	if ($testpos >= $tmaxx) { # take back last term and correct for it
	    unshift @words, pop (@line); 
	    $diff = $tmaxx - $testpos + $inc;
	}
	my $noline = @line;
	my $xcorrection = ($noline > 1) ? $diff / ($noline - 1) : 0;
	for (my $i = 0; $i < @line; $i++) {
	    $xpos += $xcorrection if ($i > 0);
	    (my $out = $line[$i]) =~ s/\(/\\\(/g;
	    $out =~ s/\)/\\\)/g;
	    $curpage->stringl($normalfont, $fs, $xpos, $ypos, $out);
	    $xpos += $fs*$curpage->string_width($normalfont, $line[$i]);

	}
	$ypos -= 1.1*$fs;
	$xpos = $tminx;
	if ($ypos < $tminy) {
	    $curpage = $root->new_page;
	    $curnumber++;
	    if ($curnumber % 2 == 0) {
		print $query->font({-face => 'verdana, arial, helvetica', -color => 'green'}, '.');
	    }
	    if ($curnumber % 10 == 0) {
		print $query->font({-face => 'verdana, arial, helvetica', -color => 'green'}, $curnumber, ' pages...');
	    }
	    ProduceHeadandFoot($pdf, $fsbase, $minx, $maxx, 
			       $miny, $maxy, $curpage, $curnumber);
	    $ypos = $tmaxy;
	}
    }
    return ($curpage, $curnumber, $ypos);

}

sub NewLine {
    
    my $root = shift;
    my $pdf = shift;
    my $curpage = shift;
    my $curnumber = shift;
    my $ypos = shift;
    my $fsbase = shift;
    my $tminy = shift;
    my $tmaxy = shift;
    my $minx = shift;
    my $maxx = shift;
    my $miny = shift;
    my $maxy = shift;
    
    $ypos -= 2.2*$fsbase;
    if ($ypos < $tminy) {
	$curpage = $root->new_page;
	$curnumber++;
	if ($curnumber % 2 == 0) {
	    print $query->font({-face => 'verdana, arial, helvetica', -color => 'green'}, '.');
	}
	if ($curnumber % 10 == 0) {
	    print $query->font({-face => 'verdana, arial, helvetica', -color => 'green'}, $curnumber, ' pages...');
	}
	ProduceHeadandFoot($pdf, $fsbase, $minx, $maxx, 
			   $miny, $maxy, $curpage, $curnumber);
	$ypos = $tmaxy;
    }
    return ($curpage, $curnumber, $ypos);
    
}


sub ProduceHeadandFoot {

    my $pdf = shift;
    my $fsbase = shift;
    my $minx = shift;
    my $maxx = shift;
    my $miny = shift;
    my $maxy = shift;
    my $page = shift;
    my $number = shift;

    my $f1 = $pdf->font('Subtype'  => 'Type1',
			'Encoding' => 'StandardEncoding',
			'BaseFont' => 'Helvetica-BoldOblique');
    my $f2 = $pdf->font('Subtype'  => 'Type1',
			'Encoding' => 'StandardEncoding',
			'BaseFont' => 'Helvetica');

    $page->stringl($f1, 4*$fsbase, $minx, $maxy - 4*$fsbase, "Textpresso");
    $page->stringr($f2, 2*$fsbase, $maxx - $fsbase/2, $maxy - 2*$fsbase, "Page $number");
    $page->line($minx + $fsbase/2, $maxy - 5*$fsbase, $maxx - $fsbase/2, $maxy - 5*$fsbase);
    $page->line($minx + $fsbase/2, $maxy - 5*$fsbase - $fsbase/6, $maxx - $fsbase/2, $maxy - 5*$fsbase - $fsbase/6);
    $page->line($minx + $fsbase/2, 3*$fsbase, $maxx - $fsbase/2, 3*$fsbase);
    my $time = scalar localtime();
    $page->stringl($f2, $fsbase, $minx + $fsbase/2, 2*$fsbase, "$time");
    $page->stringr($f2, $fsbase, $maxx - $fsbase/2, 2*$fsbase, "Produced by www.textpresso.org");
}

sub GetContents {

    my $filename = shift;
    my $return = "";
    open (IN,"$filename");
    while (my $line = <IN>) { $return .= $line }
    return $return;

}

