#!/bin/rc

awk <fe.mm 'BEGIN{
  for (i=32; i<256; ++i) c[sprintf("%c",i)]=sprintf("%c",i)
  c["<"]="&lt;"
  c[">"]="&gt;"
  c["&"]="&amp;"
  printf("<html>\n")
}
/^\.H /{
  gsub(/ \\"{{{.*$/,"")
  if (define==0 && troff==0) printf("<h%s>%s</h%s>\n",$2+1,substr($3,1,1)==sprintf("%c",34) ? substr($0,7,length($0)-7) : $3, $2+1)
  next
}
/^\.TL/{
  if (define==0 && troff==0) { printf("<head>\n<meta http-equiv=\"content-type\" content=\"text/html;charset=iso-8859-1\">\n<title>"); title=1 }
  next
}
/^\.AU/{
  if (define==0 && troff==0) 
  { 
    if (title) printf("%s</title></head>\n<body bgcolor=\"#ffffff\"><font color=\"#000000\">\n<center><h1>%s</h1></center>\n",titlestr,titlestr)
    title=0
    authorstr=substr($0,5)
    authorstr=(substr($0,5,1)==sprintf("%c",34) ? substr($0,6,length($0)-6) : substr($0,5))
  }
  next
}
/^\.AF/{
  if (define==0 && troff==0) { if (title) printf("</title></head>\n<body>\n<center><h1>%s</h1></center>\n",titlestr); title=0; }
  next
}
/^\.AS/{
  if (define==0 && troff==0) 
  { 
    if (title) printf("</title></head>\n<body>\n<center><h1>%s</h1></center>\n",titlestr)
    printf("<blockquote>\n")
    title=0
  }
  next
}
/^\.AE/{
  printf("</blockquote>\n")
}
/^\.P$/{
  if (define==0 && troff==0) printf("<p>\n")
  next
}
/^\.BL/{
  if (define==0 && troff==0) printf("<ul>\n")
  list[++level]="bl"
  next
}
/^\.VL/{
  if (define==0 && troff==0) printf("<dl>\n")
  list[++level]="vl"
  next
}
/^\.L[iI]/{
  if (define==0 && troff==0) {
    if (list[level]=="bl") printf("<li>")
    else {
      printf("<dt>")
      str=substr($0,5,1)==sprintf("%c",34) ? substr($0,6,length($0)-6) : $2
      for (i=1; i<=length(str); ++i) printf("%s",c[substr(str,i,1)])
      printf("\n<dd>")
    }
  }
  next
}
/^\.LE/{
  if (define==0 && troff==0) {
    if (list[level]=="vl") { printf("</dl>\n"); --level }
    else { printf("</ul>\n"); --level }
  }
  next
}
/^\.DS/{
  if ($1=="CB") { centered=1; printf("<center>") }
  printf("<pre>")
  display=1
  next
}
/^\.DE/{
  if (centered) { centered=0; printf("</center>") }
  printf("</pre>")
  display=0
  next
}
/^\.FS/{
  ++define
  next
}
/^\.FE/{
  --define
  next
}
/^\.de/{
  define=1
  next
}
/^\.if t \\{/{
  troff=1
  next
}
/^\.if n \\{/{
  nroff=1
  next
}
/^\\}/{
  troff=0
  if (define==0 && nroff) nroff=0
  next
}
/^\.\./{
  define=0
  next
}
/^[^.]/{
  s=""; for (i=1; i<=length($0); ++i) s=s c[substr($0,i,1)]
  if (define==0 && troff==0 && title==0) printf("%s\n",s)
  if (title) titlestr=titlestr s
# if (display) printf("<wbr>\n") 
  next
}
END{
  printf("<address>%s</address>\n</body>\n</html>\n",authorstr)
}' | sed -e 's|\\\*V|<var>|g
s|\\\*v|</var>|g
s|\\\*C|<code>|g
s|\\\*c|</code>|g
s|\\\*A\(.*\)\\\*a|<a href="\1">\1</a>|g
s|\\\*E|<em>|g
s|\\\*e|</em>|g
s|\\\*K|<kbd>|g
s|\\\*k|</kbd>|g
s|\\-|-|g
s|\\(en|-|g
s|\\&||g' >fe.html
