#!/usr/local/bin/perl -w

print "Content-type: text/html\n\n";

$filename = $ENV{'QUERY_STRING'};
@args = split /\&/,$filename;

$width=3;          # width
%mark = ();        # mark lines
$mark_a='<b>';
$mark_e='</b>';
$bgcolor = '';
$fgcolor = '';

sub mkcolor {
	my ($x) = @_;
	if($x =~ /^[0-9a-eA-E]+$/){
		return "#$x";
	} else {
		return $x;
	}
}

if(@args > 1){
	foreach $x (@args){
		if($x =~ /(.*)=(.*)/) {
			$k = $1; 
			$v = $2;
			if($k eq 'lines'){
				$width = $v;
			}
			if($k eq 'file'){
				$filename = $v;
			}
			if($k =~ /mcolou?r/){				
				$mark_a = '<font color=' . mkcolor($v) . '>';
				$mark_e = "</font>";
			}
			if($k =~ /bgcolou?r/){
				$bgcolor = 'bgcolor=' . mkcolor($v);
			}
			if($k =~ /fgcolou?r/){
				$fgcolor = 'text=' . mkcolor($v)
			}
			if($k eq 'mark'){
				foreach $x (split ',',$v){
					if($x =~ /(.*)-(.*)/){
						$a = $1;
						$e = $2;
						if($e - $a > 1000) {
							$e = $a + 1000;
						}
						foreach $y ($a .. $e){
							$mark {$y} ++;
						}
					} else {
						$mark{$x} ++;
					}
				} 
			}
		} else {
			$filename = $x;
		}
	}
}

print "<html><head><title>$filename</title></head><body $bgcolor $fgcolor><pre>\n";
if(-e $filename){
	if(open FILE, "<$filename"){			
		$line = 1;
		while(<FILE>){
			s/&/&amp;/g;
			s/</&lt;/g;
			s/>/&gt;/g;
			if($mark{$line}){
				print $mark_a;
			}
			if($width){
				print (sprintf ('<i>%' . $width . 'd</i> ' , $line));
			}
			print;
			if($mark{$line}){
				print $mark_e;
			}
			$line ++;
		}
		close FILE;
	} else {
		print "$filename could not be opened: $!\n";
	}
} else {
	print "$filename does not exist.\n";
}
print "</pre></body></html>\n";
