#!/usr/bin/perl

# loop through all files on command line

$found_head_1 = 0;  # parsing a <h1>, haven't found </h1> 
$found_title = 0;   # parsing a <title>, haven't found </title>
$level_1 = 0;	    # have commenced a set of level 1 heads
$level_2 = 0;       # have done a level 2 head

sub reset_head {
	# reset lower levels, terminating list if needed
	if ($level_2) {
	    print "</ul>\n";
	}
	if ($level_1) {
	    print "</ul>\n";
	}
	$level_1 = 0;
	$level_2 = 0;
}

sub preamble {
    print "<html>\n<head>\n";
    print "<title> Topics in OS lectures </title>\n";
    print "</head>\n\n<body>\n";
    print "<h1> Topics in OS lectures </h1>\n";
}

do preamble();

while ($_ = <ARGV>) {

    # this part replaces patterns <title> ... </title> with
    # <h2> ... </h2> <ul>

    if (/<title>(.*)<\/title>/) {
	do reset_head();
	print "\n\n<h2>", $1, "</h2>\n\n";
	next;
    }
    if (/<title>(.*)/) {
	do reset_head();
	print "\n\n<h2>", $1;
	$found_title = 1;
	next;
    }
    if ($found_title && /<\/title>/) {
        print "</h2>\n\n";
	$found_title = 0;
	next;
    }
    if ($found_title) {
	print;
    }

    # handle <h1> ... </h1>
    # turn it into <li> ...
    # add <ul> if this is the first of these

    if (/<[Hh]1>(.*)<\/[Hh]1>/) {
	if ( ! $level_1) {
	    print "<ul>";
	}
        print "<li>", $1, "\n";
	$level_1 = 1;
	next;
    }

    if (/<[Hh]1>(.*)/) {
	print "<li>", $1, "\n";
	$found_head_1 = 1;
	$level_1 = 1;
	next;
    }
    if ($found_head_1 && /<\/[Hh]1>/) {
	$found_head_1 = 0;
	next;
    }
    if ($found_head_1) {
	print;
    }

}
