#! /cygdrive/c/Perl/bin/perl
#
# A PERL script that takes a bibtex file as input and creates a file called 
# <whatever>.bib.html which should be a html file that can be copied and 
# pasted into a bib file.
#
# Written by Margaret McGaley (mmcgaley@cs.nuim.ie) in an afternoon. 
# No guarantees or even promises.
#
# WARNING: If the file <whatever>.bib.html already exists, this will overwrite 
# it
#
# Feel free to copy and/or modify.

# Take the first argument to be the filename we want to htmlise
$filename = $ARGV[0];

# If it's not called <whatever>.bib, exit with an error
if (!($filename =~ /\w+\.bib/)) {
	die "Please specify a bibtex file.";
}

# Try to open the file 
open $infile, $filename or die "Can't find file $filename. Quitting ...";

open $outfile, ">$filename.html" or die "Failed to open output file. Quitting.";

print "Printing html to $filename.html";

print $outfile "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n";
print $outfile "<HTML><HEAD><TITLE>$filename.html</TITLE>\n";
print $outfile "<META http-equiv=Content-Type content=\"text/html; charset=iso-8859-1\">\n";
print $outfile "</HEAD>\n";
print $outfile "<BODY>\n\n";
print $outfile "<p>This HTML was created from $filename using <a href=\"http://www.cs.nuim.ie/~mmcgaley/Download/htmliser.pl\">htmliser.pl</a> Each bibentry can be linked with #key.</p>";

while (<$infile>) {
	# This is attempting to match 
	# @<entrytype> { <entryname>,
	if (/(\s*@\w+\{)([\w:]+),/) {
		print $outfile "<p> $1 <a name=\"$2\">$2</a>,\n";
	}
	# This should match
	# <anything> = <anything else>
	elsif (/\s*\w+\s*=\s*[\w{}]\s*,?\s*/) {
		print $outfile "<br> &nbsp;&nbsp;&nbsp;&nbsp;", $_;
	}
	# Closing brace
	elsif (/\s*}\s*/) {
		print $outfile "<br> $_ </p>\n";
	}
	else {
		print $outfile "<p>", $_, "</p>\n";
	}
}

print $outfile "</html></body>\n\n";

