#! /usr/bin/perl -w

# convert_toc.pl converts old <<TOC>> marked up files to use the new
# <Section> syntax (suitable for processing by HTMLPlug -description_tags

my $line = "";
my $foundbody = 0;
my $level = 0;
while (defined ($line = <STDIN>)) {

    $line =~ s/[\cJ\cM]+$//;
    if (!$foundbody) {
	print STDOUT "$line\n";
	$foundbody = 1 if ($line =~ /<body/i);
	next;
    }

    # sort out the <<I>> image tags
    $line =~ s/&lt;&lt;I&gt;&gt;\s*(\w+\.(?:png|jpe?g|gif))/<center><img src=\"$1\"><\/center><br>\n/igs;

    if ($line =~ /&lt;&lt;TOC(\d+)&gt;&gt;(.*)/) {
	my $thislevel = $1;
	my $title = $2;
	$title =~ s/<[^>]+>//g;
	$title =~ s/^\s+//;
	$title =~ s/\s+$//;

	# print out any tags that were on the line
	while ($line =~ s/(<[^>]+>)//) {
	    print STDOUT $1;
	}

	print STDOUT "\n<!--\n";

	if ($thislevel <= $level) {
	    for (my $i = 0; $i < ($level-$thislevel+1); $i++) {
		print STDOUT "</Section>\n";
	    }
	}
	print STDOUT "<Section>\n";
	print STDOUT "  <Description>\n";
	print STDOUT "    <Metadata name=\"Title\">$title</Metadata>\n";
	print STDOUT "  </Description>\n";
	print STDOUT "-->\n";

	$level = $thislevel;

    } elsif ($line =~ /<\/body>/i) {
	$line =~ /^(.*?)(<\/body>.*)$/i;
	print STDOUT $1 if defined $1;
	print STDOUT "\n<!--\n";
	for (my $j = 0; $j < $level; $j++) {
	    print STDOUT "</Section>\n";
	}
	print STDOUT "-->\n";
	print STDOUT $2 if defined $2;
	print STDOUT "\n";

    } else {
	print STDOUT "$line\n";
    }
}
