#! /usr/bin/perl
# Look for
#   Algorithm: (name)
#   ...
#   End Algorithm: (name)
# check that algorithm names match
#
$within_alg = 0;
$within_comment = 0;
$name = "";

for (@ARGV) {
    if (/-latex/) { $latex = 1; }
    elsif (/-html/) { $html = 1; }
    elsif (/-text/) { $text = 1; }
    elsif (/^-/) {
	print STDERR "Unrecognized argument $_\n";
    }
    else { $filename = $_; }
}

open( INFD, "<$filename" ) || die "Cannot open $filename\n"; 
&printBOP;
while (<INFD>) {
    if (/\/\*/)  { $within_comment = 1; }
    if (/\*\//) { $within_comment = 0; }
	
    if (/End\s+Algorithm:\s*([^\s]*)/) {
	if ($within_alg != 1 || $1 ne $name) {
	    print STDERR "Unexpected algorithm end for $1\n";
	}
	&printTrailer( $name );
	$within_alg = 0;
    }
    elsif (/Algorithm:\s*([^\s]*)/) {
	$name       = $1;
	if ($name ne "") {
	    $within_alg = 1;
	    print "Within alg $name\n" if $debug;
	    &printHeader( $name );
	}
    }
    elsif ($within_alg) {
	if (!$within_comment) {
	    print STDERR "Comment ended without ending algorithm $name\n";
	    $within_alg = 0;
	}
	else {
	    if ($html) {
		&transformHTML;
	    }
	    print $_;
	}
    }
}
&printEOP;

# ------------------------------------------------------------------------
# For each item, generate text that surrounds the description
sub printHeader {
    my $name = $_[0];
    if ($latex) {
	print "\\section{$name}\n";
    }
    elsif ($html) {
	print "<h2><A name=#$name>$name</a></h2>\n";
    }
    else {
	print "Algorithm for routine $name\n";
    }
}
sub printTrailer { 
    my $name = $_[0];
}

sub transformHTML {
    s/&/&AMP;/g;
    s/</&lt;/g;
    s/>/&gt;/g;
    if (/^\s*$/) {
	$_ = "<BR>\n";
    }
}
#
# --------------------------------------------------------------------------
# Code to create stand-alone documents 
sub printBOP {
    if ($html) {
	print "<HTML>
<HEAD><TITLE>Algorithms</TITLE></HEAD>
<BODY BGCOLOR=\"FFFFFF\">\n";
    }
}

sub printEOP {
    if ($html) {
	print "</BODY>\n</HTML>\n";
    }
}
