#! /usr/bin/gawk -f
# Last edited on 2023-02-28 16:21:56 by stolfi

BEGIN { 
  FS = "|"; 
  inlist = 0;   # If {inlist} is true, we are inside a list of entries.
  copying = 0;  # If {inlist} and {copying} are true the entries must be printed.
}

/^ *[#][*]/ { 
  # General comment to be printed:
  if (inlist) { data_error("visible comment inside list"); }
  make_parag($0);
  next;
}

/^ *[#][-]/ { 
  # Start of section to omit:
  if (inlist) { data_error("missing section end marker"); }
  inlist = 1;
  copying = 0;
  next;
}

/^ *[#][+]/ { 
  # Start of section to convert:
  if (inlist) { data_error("missing section end marker"); }
  start_section($0); 
  inlist = 1;
  copying = 1; 
  next;
}

/^ *[#][/]/ { 
  # End of section list:
  if (! inlist) { data_error("spurious end marker"); }
  if(copying) { end_section(); }
  inlist = 0;
  copying = 0; # Irrelevant while {inlist} is false.
}
  
/^ *[#]/ { 
  # Internal comment, ignore:
  next;
}

/^ *$/ {
  # Blank line, ignore:
  next;
}

// { 
  # Table entry line:
  if (copying == 0) { next; }
  if (NF != 6) { data_error("wrong number of columns = " NF); }
  yr = clean($1);
  pt = clean($2);
  en = clean($3);
  ot = clean($4);
  le = clean($5);
  au = clean($6);
  make_entry(yr, pt, en, ot, le, au);
  next;
}

END { 
  if (inlist) { data_error("missing section end marker"); }
}

function start_section(lin) {
  gsub(/^[-+ #]+/, "", lin);
  gsub(/[ ]+$/, "", lin);
  printf "\n<h3 style=\"background-color:#ffee88;\">%s</h3>\n", lin;
  printf "\n"
  printf "<ul>\n"
}

function end_section() {
  printf "</ul>\n"
}

function make_parag(lin) {
  gsub(/^[# *]+/, "", lin);
  gsub(/[ ]+$/, "", lin);
  printf "<p>%s</p>\n", lin;
}

function make_entry(yr,pt,en,ot,le,au, na1,na2,na3) {
  na1 = pt;
  na2 = (en == "" ? "" : ("EN: " en));
  na3 = ot;
  if (na2 == "") { na2 = na3; na3 = ""; }
  if (na1 == "") { na1 = na2; na2 = na3; na3 = ""; }
  printf "  <li>%s %s, %s", yr, edtit(na1, "b"), au;
  if (na2 != "") {
    printf " (%s", edtit(na2, "");
    if (na3 != "") {
      printf ", %s", edtit(na3, "");
    }
    printf ")"
  }
  printf "</li>\n"
}

function clean(x) {
  # Removes leading and trailing spaces:
  gsub(/^[ ]+/, "", x);
  gsub(/[ ]+$/, "", x);
  return x;
}

function edtit(x,b, lc,tx,mk) {
  # Edits a title, processing the leading language code.
  fa = (b == "b" ? "<b>" : "");
  fb = (b == "b" ? "</b>" : "");
  if (x == "") {
    return x
  } else if (x ~ /^[A-Z][A-Z]:/) {
    lc = substr(x, 1, 2); 
    tx = (lc ": <i>" fa clean(substr(x, 4)) fb "</i>");
  } else { 
    lc = ""; tx = ("<i>" fa x fb "</i>");
  }
  return tx;
}

function arg_error(msg) {
  printf "** %s\n", msg > "/dev/stderr";
  exit(1);
}

function data_error(msg) {
  printf "%s:%d: ** %s\n", FILENAME, FNR, msg > "/dev/stderr";
  printf "  [%s]\n", $0; 
  exit(1);
}