#!/usr/bin/perl -w
use vars qw($d);

($file=shift) =~ s|\.doc$||;
open(IN,"$file.doc") or die "could not find $file.doc\n";
open(OUT,">$file.shtml") or die "could not open $file.shtml\n";
print OUT <<EOF;
<!--#include virtual="0blok1.inc" -->
<title>$file</title>
<!--#include virtual="0blok2.inc" -->
EOF

$intab=$name=0;
while(<IN>) {
  chomp;
  replace();
  s|\\item(.*)|<li>$1</li>|;
  s|^UL$|<ul>|;         # unordered list
  s|^ENDUL$|</ul>|;
  s|^OL$|<ol>|;         # ordered list
  s|^ENDOL$|</ol>|;
  s|^DL$|<dl>|;         # description list
  s|^ENDDL$|</dl>|;

  /^$/ and do {
    print OUT "\n";
  },next;
  /^NAME/ and do {
    s|^NAME\s+||;
    print OUT "<h1>$_</h1><h2>";
    $name=$_;
  },next;
  /^SHORT/ and do {
    s|^SHORT\s+||;
    print OUT "$_</h2><p/>\n";
  },next;
  /^TYPE/ and do { 
    ($d,$return)=split;
  },next;
  /^PNG / and do {
    s|^PNG (.*)|<p><img src="graphics/$1.png" alt="$1"/></p>|;
    print OUT "$_";
  },next;
  /^FILE / and do {
    s|^FILE ||;
    verbatim("$_");
  },next;
  /^ARG/ and do {
    $intab or ptabhead();
    $intab=1;
    $line=join('<td>',split(/\s+/,$_,5));
    $line=~s|^ARG||;
    $line=~s|<td>-|<td>|g;
    print OUT "<tr>$line\n";
  },next;
  /^HEAD\s+(.*)/ and do {
    $intab and ptabtail();
    $intab=0;
    print OUT "<h2>$1</h2>";
  },next;
  /^PAR$/ and do {
    print OUT "\n<p></p>\n";
  },next;
  /^TAB/ and do {
    print OUT "<table class=\"simplot\">\n";
    while (<IN>) {
      last if /^ENDTAB/;
      replace();
      s/\s*\|\s*/<td>/g;
      s/.*/<tr><td>$&/;
      s/<td>\\b/<td class="simplot">/g;
      print OUT;
    }
    print OUT "</table>\n";
  },next;
  /^VERB/ and do {
    print OUT "<pre>\n";
  },next;
  /^ENDVERB/ and do {
    print OUT "</pre>\n";
  },next;

  print OUT "$_\n";
}
print OUT <<EOF
<!--#include virtual="0blok3.inc" -->
<!--#config timefmt="%Y-%m-%d %X %Z" -->
<!--#echo var="LAST_MODIFIED" -->
<!--#include virtual="0blok4.inc" -->
EOF
;

sub ptabhead {
  print OUT "<table class=\"simplot\"\n".
            "<tr><th>parameter<th>type<th>units<th>description\n";
}
sub ptabtail {
  print OUT "<tr><td class=\"simplot\">returns:<td>$return\n".
            "</table>\n";
}
sub verbatim {
  $file=shift;
  open(FILE,$file) or die "$file not found\n";
  print OUT "<pre>\n";
  while(<FILE>) {
    next if /^#!/;
    replace();
    print OUT;
  }
  print OUT "</pre>\n";
  close FILE;
}
sub replace { # this is done on the input lines before anyting else
  s|\&|\&amp;|g;
  s|\\le |\&le; |g;
  s|\\ge |\&ge; |g;
  s|\\lt |\&lt; |g;
  s|\\gt |\&gt; |g;
  s|<|\&lt;|g;
  s|>|\&gt;|g;
  s|\\this|\\rout $name|g if $name;
  s|\\arg\s+(\S+)|<b>$1</b>|g;
  s|\\rout\s+(\w+)|<a href="$1.shtml">$1</a>|g;
  s|\\\\|<br>\n|;
  s|\^(\d+)|<sup>$1</sup>|g;
  s|\\dt\s+(\S+)|<dt>$1</dt><dd>| and do { s|([^_])_|$1 |; s/ _/_ /; s/$/<\/dd>/; };
  s|\\_|_|g;
  s|\\it\s+(\S+)|<i>$1</i>|g;
  s|\\tt\s+(\S+)|<kbd>$1</kbd>|g;
}
