#!/usr/local/bin/perl


sub fetch_data{

	local($instr) = @_;
	local($g_step, @g_info);


	$instr =~ /^(\w*)/;
	$instr = $1;

	$g_step = &get_offset($instr);

	if ($g_step > 0){
		@g_info = &load_info($g_step);
		&emit_nice_format(@g_info);
	}
	else {
		print "no match\n";
	}

}

sub get_offset {

	local($instr) = @_;
	local($i);

	$instr =~ tr/A-Z/a-z/;

	dbmopen(%OFFSET, "/archives/www/httpd/htdocs/personal/pborwein/BOOK/PROTECTED/Indexing/src/offset", 0644);

	$i = $OFFSET{$instr};

	if ($i eq "" ){
		return -1;
	}
	else{
		return $i;	
	}

	dbmclose(%OFFSET);

}

sub load_info {

	local($ppibook);

	local($l_step) = @_;
	local($l_line);
	local(@l_info);
	local($j);
	
	$ppibook = "/archives/www/httpd/htdocs/personal/pborwein/BOOK/PROTECTED/Indexing/src/ppibook.idx";
	$j = 0;

	open(DATA, "$ppibook");

	seek(DATA, $l_step-1,0);

	$l_line = <DATA>;
	$l_line = <DATA>;

	while ($l_line =~ /\d+:\d+:\d+/){
		chop($l_line);
		$l_info[$j++] = $l_line; 
		$l_line = <DATA>;
		
	}


	close(DATA);

	return @l_info;
}


sub emit_nice_format{

	local(@l_info) = @_;
	local($code, $chapter, $page, $line);
	local($lchapter, $lpage, $lline);

	$lchapter = 0;
	$lpage= 0;
	$lline = 0;


	print "<H5>\n";
	print "<UL>\n";
	foreach $code (@l_info){
	
		($chapter, $page, $line) = split(/:/, $code);
		$cl =  &Get_line($chapter,$line);	



		if ($lchapter == $chapter){

			if ($lpage == $page){
				print "<LI> $cl";
	
			}
			else{
				if ($lline > 0){
					print "</UL>";
				}

				print "<LI> <A HREF=\"/cgi-bin/pindex2\?$page\">Page $page</A>";
				print "<UL>";
				print "<LI> $cl";

			}

		}else{

				
				if ($lpage > 0){
					print "</UL>";
					print "</UL>";
				}

				print "<LI> Chapter $chapter";
				print "<UL>";
				print "<LI> <A HREF=\"/cgi-bin/pindex2\?$page\">Page $page </A>";
				print "<UL>";
				print "<LI> $cl";

		}

		$lchapter = $chapter; $lpage=$page; $lline=$line;
	}

	print "</UL>\n";
	print "</H5>\n";

}


sub Get_line{

local ($chapter, $line) = @_;
local($i);

open(TMP, "/archives/www/httpd/htdocs/personal/pborwein/BOOK/PROTECTED/Indexing/src/ch-$chapter.tex")||print "die\n";

$i=1;
while($a=<TMP>){

	if ($i == $line){
		last;
	}
	$i++; 

}

close(TMP);
return $a;

}

1;
