#!/usr/bin/perl -w

use Exception ':try';

# Forward declarations
sub openFile;
sub toHTML;

# Define a constant
use constant FILEIO_ERR => 'Please check if the specified file exists.';

print "Content-Type: text/html\n\n";
print toHTML('file2html.pl');

sub openFile {
	my $mode = shift;
	my $filename = shift;
	
	local *FILE;
	open FILE, "$mode$filename" or
		throw Exception("File \"$filename\" cannot be opened: $!", FILEIO_ERR);
	return *FILE;
}

# convert to HTML
sub toHTML {
	my $filename = shift; 
	my $html = "<html>\n<head><title>$filename</title></head>\n<body>\n";
	
	try {
		local *FILE;
		*FILE = openFile('<', $filename);
		$html .= "<pre>\n";
		my $line = '';
		while ($line = <FILE>) {
			$line =~ s/&/&amp;/g;
			$line =~ s/</&lt;/g;
			$line =~ s/>/&gt;/g;
			$line =~ s/\t/' ' x 4/ge;
			$html .= $line;
		}
		close FILE;
		$html .= "</pre>\n";
	} catch Exception with {
		my $err = shift;
		$html .= "<h1>Error</h1><br>\n<div style='color: #FF0000'><b>$err</b></div>\n";
		$html .= "<h2>Suggested Action</h2><br>\n<div>" . $err->solution() . "</div>\n";
		$html .= "<h2>Stacktrace</h2><br>\n<pre>\n" . $err->stacktrace() . "</pre>\n";
	} catch Error::Simple with {
		my $err = shift;
		$html .= "<h1>Error</h1><br>\n<div style='color: #FF0000'><b>$err</b></div>\n";
	};

	$html .= "</body>\n</html>\n";
}
