#!/usr/bin/perl -w

use strict;

my %txtcolor = ( ">>>", "#880088",
		 "<<<", "#000000",
		 "err", "#ff0000",
		 "inf", "#00aa00",
		 "CMD", "#8800ff",
		 "INF", "#00aa00",
		 "ERR", "#ff0000",
		 "TXT", "#000000"
	       );
my %lblcolor = ( ">>>", "#cc0088",
		 "<<<", "#cc0088",
		 "err", "#cc0088",
		 "inf", "#cc0088",
		 "CMD", "#8800ff",
		 "INF", "#8800ff",
		 "ERR", "#8800ff",
		 "TXT", "#8800ff"
	     );
my %add = ( ">>>" => ">",
	    "CMD" => ">",
	  );
my @bold = ( ">>>", "err", "CMD", "ERR" );
my %bold = (); $bold{$_}=1 for (@bold);

sub bold {
  print "<b>";
}
sub unbold {
  print "</b>";
}

sub italic {
  print "<i>";
}
sub unitalic {
  print "</i>";
}
sub color {
  my $col = shift;
  $col = $txtcolor{$col} if exists $txtcolor{$col};
  print "<font color=\"", $col,"\">";
}
sub lblcolor {
  my $col = shift;
  $col = $lblcolor{$col} if exists $lblcolor{$col};
  print "<font color=\"", $col,"\">";
}
sub uncolor {
  print "</font>";
}
sub br {
  print "<br>\n";
}
sub par {
  print "<p>\n";
}
sub htmlify {
  my $str = shift || "";
  $str =~ s/\033.*?m//g;
  $str =~ s/\&/&amp;/g;
  $str =~ s/\</&lt;/g;
  $str =~ s/\>/&gt;/g;
  while ($str =~ s/  /\&nbsp; /) { }
  print $str;
}

print <<"EOF";
<html>
<head><title>Generated by cmdlog2html</title></head>
<body bgcolor="#FFFFFF">
EOF

my $lastlbl = undef;

while (<>) {
  chomp;
  /^\s*$/ and next;
  my ($code, $source, $text) = split(/\s+/,$_,3);
  par() if defined($lastlbl) && $source ne $lastlbl;
  lblcolor( (!defined($lastlbl) || $source ne $lastlbl) ? $code : "white" );
  htmlify("$source");
  uncolor();
  htmlify("    ");
  my $bold = exists($bold{$code});
  bold() if $bold;
  color($code);
  htmlify($text);
  uncolor();
  unbold() if $bold;
  br();
  $lastlbl = $source;
}

print <<"EOF";
</body>
</html>
EOF
