#! /usr/bin/gawk -f
# Last edited on 2000-06-14 04:54:06 by stolfi

BEGIN {
  abort = -1;
  usage = ( ARGV[0] " [ -v title=STRING ] < INFILE.grx > OUTFILE.html" );
  
  # Reads a grammar in ".grx" format, outputs a nice
  # HTML rendering of the same.
  # If the title is specified, outputs the HTML header end trailer,
  # as well as a <H1> title. Otherwise those items are omitted.
  
  if (numcolor == "") { numcolor = "404040"; }
  if (cmtcolor == "") { cmtcolor = "007f00"; }
  if (defcolor == "") { defcolor = "600000"; }
  if (ntscolor == "") { ntscolor = "a00040"; }
  if (bgcolor == "")  { bgcolor =  "ffffff"; }
  
  if (title != "") { output_html_head(title); }
  
  printf "<font color=\"#%s\">\n", numcolor;
  printf "<b><tt><pre>\n";
}

/^ *$/ {
  printf "\n";
  next;
}

/^ *[#] *Data-File *:/ {
  next;
}

/^ *[#]/ {
  cmt = $0; 
  sub(/# =/, "===", cmt); 
  sub(/# -/, "---", cmt); 
  sub(/#/, " ", cmt); 
  printf "<font color=\"#%s\"><i>%s</i></font>\n", cmtcolor, html_protect(cmt);
  next;
}

/^[A-Z()].*[:]/ {
  name = $0; gsub(/ *[:] *$/, "", name);
  printf "<a name=\"%s\">\n", html_protect(name);
  printf "<font color=\"#%s\">%s</font>:\n", ntscolor, html_protect(name);
  next;
}

/./ {
  match($0, /[ ][^ ]+[ ]*$/);
  cts = substr($0,1,RSTART);
  def = substr($0,RSTART+1);
  printf "<font color=\"#%s\">%s</font><font color=\"#%s\">%s</font>\n", 
    numcolor, html_protect(cts), 
    defcolor, html_protect(def);
  next;
}

END {
  printf "</pre></tt></b>\n";
  printf "</font>\n";

  if (title != "") { output_html_tail(); }
  
}

function output_html_head(title)
{
  printf "<html>\n";
  printf "<head>\n";
  printf "<title>%s</title>\n", html_protect(title);
  printf "</head>\n";
  printf "<body bgcolor=\"#%s\">\n", bgcolor;
  printf "<h1>%s</h1>\n", html_protect(title);
}

function output_html_tail()
{
  printf "</body>\n";
  printf "</html>\n";
}

function html_protect(txt)
{
  gsub(/&/, "\\&amp;", txt);
  gsub(/</, "\\&lt;", txt);
  gsub(/>/, "\\&gt;", txt);
  gsub(/\n/, "<br>", txt);
  return(txt);
}