#!/usr/bin/perl
#
# Convert a message on a mailing list to html
#
$foot='^APO APO APO APO APO  Apache Point Observatory 3.5m  APO APO APO$';
{
   $text = "";			# body of text
   $indexfile = "INDEX.html";

   while(<>) {
      if(/^\s*$/) { # end of mail header
	 while(($_ = <>) && /^\s+$/) {;} # skip blanks
	 $text = $_;
	 if(/$foot/o) {		# empty body of message
	     $empty_body=1;
	 }
	 last;
      }

      if(/^Date:\W+(.*)/) {
	 ($date) = $1;
      } elsif(/^From:/) {
	 if(/^From:\W+([^(])\W+\((.+)\)/) {
	    ($author) = $1;
	 } elsif(/^From:\W+"([^<]+)"\W+<(.+)>/) {
	    ($author) = $1;
	 } elsif(/^From:\W+([^<]+)\W+<(.+)>/) {
	    ($author) = $1;
	 } elsif(/^From:\W+(\S+)\W+/) {
	    ($author) = $1;
	 }
      } elsif(/^Subject:\W+(.*)/) {
	 ($subject) = $1;
      }
   }

   if($empty_body != 1) {
      while(<>) {
	 $text = $text . $_;
	 if(/$foot/o) {
	    last;
	 }
      }
   }

   while(<>) {
      if(/APO  This is message (\d+) in the /) {
	 ($msg) = $1;
      }
      $text = $text . $_;
   }
   #
   # quote characters special to HTML
   #
   foreach ('$author', '$date', '$subject', '$text') {
      eval "$_ =~ s/&/&amp;/g;";
      eval "$_ =~ s/</&lt;/g;";
      eval "$_ =~ s/>/&gt;/g;";
   }				
   # 
   # and finally generate the required text
   #
   print "<Title> $subject </Title>\n";
   print "<H1>Subject: $subject </H1>\n";
   print "<H2>From: $author</H2>\n";
   print "<H2>Submitted: $date</H2>\n";
   $next = $msg + 1;  $prev = $msg - 1;
   print "<H2>Message number: $msg\n";
   print "(previous: <a href=\"./msg.$prev.html\">$prev</a>,\n";
   print "next: <a href=\"./msg.$next.html\">$next</a>\n";
   print "up: <a href=\"./INDEX.html\">Index</a>)\n";
   print "</H2><p>\n\n\n";
   print "<pre>\n";
   print $text;
   print "</pre>\n";
   #
   # Done with HTMLising the document, now add it to the index
   #
   ($dayname, $day, $month, $year) = split(/[,\s]+/,$date);
   rename("$indexfile","$indexfile~");
   open(INDEX,">$indexfile") || die("Can't open $indexfile\n");
   open(BINDEX,"<$indexfile~") || die("Can't open backup for $indexfile\n");
   while(<BINDEX>) {
      print INDEX;
      if($_ =~ m|^<dl>$|i) {
	 print INDEX "<dt> Message <a href=\"./msg.$msg.html\"> $msg</a>:\n";
	 print INDEX "<dd> $subject\n";
	 print INDEX "($author; $day $month $year)\n";
      }
   }
   close(INDEX); close(BINDEX);

   exit 0;
}
