#!/usr/bin/perl -w

$filename = "docs/commands.html";

if ($ARGV[1]) 
{
    $filename = $ARGV[1];
}

main();

sub main
{

    if ( (open IN, "<$filename") && (open OUT, ">docs/imcom.7") ) 
    {
	my @LINES = <IN>;

	while ($LINES[0] !~ /<!-- Content/)
	{
	    # Throw away the header
	    shift @LINES;
	}

	# throw away the content line
	shift @LINES;


	print OUT ".\".This is the man page for imcom commands\n" .
	    ".\".TH IMCOM 7 March 25, 2002 IMCOM(7)\n" .
	    ".Dd March 25, 2002\n" .
	    ".Dt IMCOM 7\n" .
	    ".Os IMCOM(7)\n" .
	    ".Sh NAME\n" .
	    "imcom interactive commands\n" .
	    ".Sh DESCRIPTION\n" .
	    "This manual page describes the commands that can be used within imcom.  This page holds the same information as the online help.\n" .
	    ".Sh COMMANDS\n" .
	    ".Bl -tag -width Fl\n";

	# parse until we get to the footer
	while ($LINES[0] !~ /<!-- Content/)
	{
	    if ($LINES[0] =~ /<a name=/) 
	    {
		shift @LINES;
		add_command(\@LINES, OUT);
	    }
	    shift @LINES;

	}

print OUT ".El\n.Sh SEE ALSO\n" .
    ".Xr imcom 1\n" . 
    ".Sh AUTHOR\n" .
    "This man page is generated by a script written by James Morrison\n" .
    ".Pa <ja2morrison\@student.math.uwaterloo.ca>\n" .
    "for a reference to all interactive commands in\n" .
    ".Ic imcom .";


	close IN;
	close OUT;
    }
    else
    {
	print STDERR "Cannot open $filename or docs/imcom.7\n";
	exit 1;
    }
}

sub add_command
{
    my ($lines, $filehandle) = @_;
    my ($command, $example, $explain);

    if ($$lines[0] =~ /<p><b>(.*)<\/b>(&nbsp;)*(.*)<br>/)
    {
	$command = $1;
	$example = $3;

	shift @{$lines};

	while ($$lines[0] !~ /<\/p>/)
	{
	    $explain .= $$lines[0];
	    shift @{$lines};
	}
	$$lines[0] =~ /(.*)<\/p>/;
	$explain .= $1;

	# print the output.
	print $filehandle ".It Ic $command Op $example\n";  
	print $filehandle "$explain\n";

	if ($$lines[1] =~ /<ul>/)
	{
	    shift @{$lines};
	    shift @{$lines};

	    add_list($lines, $filehandle);
	}
    }
}

sub add_list
{
    my ($lines, $filehandle) = @_;
    my ($var, $explain, $list);

    $list = ".Bl -tag -width Fl\n";


    while ($$lines[0] !~ /<\/ul>/)
    {
	$$lines[0] =~ /<li><b>(.*)<\/b>:\s*(.*)<\/li>/;
	$var = $1;
	$explain = $2;

	$list .= ".It Ic $var\n$explain\n";
	shift @{$lines};
    }
    if ($$lines[0] =~ /<li><b>(.*)<\/b>:\s*(.*)<\/li>/)
    {
	$var = $1;
	$explain = $2;

	$list .= ".It Ic $var\n$explain\n.El\n";
    }

    # print the output.
    print $filehandle "$list";
}
