#!/usr/bin/perl

use strict;
use warnings;

# run this like "perl nh_htmlize.pl src/*.c" in the nethack src root dir.

my $indexfile = "index.html";

my $htmlized_prepend = "<html><html></head><body><pre>\n";
my $htmlized_append  = "\n</pre></body></html>";

my @filenames;
my %functions;

open(INDEXFILE, ">" . $indexfile);

print INDEXFILE "<html>\n";
print INDEXFILE "<head>\n";
print INDEXFILE "</head>\n";
print INDEXFILE "<body>\n";

sub process_file {

    my $filu = shift;
    my $curline = 1;

    open(INFO, $filu)   or die "Couldn't open file $filu: $!\n";
    my @lines = <INFO>;
    close(INFO);

    open(HTMLIZED, ">".$filu.".html");
    print HTMLIZED $htmlized_prepend;

    foreach $a (@lines) {
	print HTMLIZED '<span id="line'.$curline.'">'.sprintf("%4u. ",$curline).$a;

	if ($a =~ m/^([a-z_0-9]+\(.*\))\s*$/i) {
	    my $fnc = $1;
	    $functions{$fnc} = [$filu, ($curline-1)];
	}

	$curline++;
    }

    print HTMLIZED $htmlized_append;
    close(HTMLIZED);

    push @filenames, $filu;
}

while ($#::ARGV) { process_file($::ARGV[0]); shift; }

print INDEXFILE '<span style="width:50%;float:right;"><ul>';
foreach $a (@filenames) {
    print INDEXFILE '<li><a href="'.$a.'.html">'.$a.'</a>'."\n";
}
print INDEXFILE "</ul></span>";

print INDEXFILE '<span style="float:left;"><ul>';

for my $key (sort { lc($a) cmp lc($b) } keys %functions) {
    print INDEXFILE '<li><a href="'.$functions{$key}->[0].'.html#line'.$functions{$key}->[1].'">'.$key.'</a>'."\n";
}

print INDEXFILE "</ul></span>";


print INDEXFILE "</body>\n";
print INDEXFILE "</html>\n";
close(INDEXFILE);
