#! /usr/bin/gawk -f
# Last edited on 2025-07-25 03:07:55 by stolfi

# Converts pixel coordinates from a map image to
# geographical coordinates.

BEGIN {
  # Writes files "p2c_out_{tag}.txt" for plotting.
  # Writes single file for wikipedia.
  # Scale factors (pixel to degrees). Index 0 is SN, index 1 is WE.
  split("", scale);
  for (i = 0; i <= 1; i++) { scale[i] = 0; }
  pfile = ""; # Current plot file:
  wfile = "p2c_out_wiki.txt"
  tag = "?";
}

// { gsub(/[ ]*[#].*$/, "", $0); }

/^[ ]*([#]|$)/ { next; }

/^scaleSN[ ]+=[ ]+/ { setscale(0); next; }

/^scaleWE[ ]+=[ ]+/ { setscale(1); next; }

function setscale(i) {
  scale[i] = (($3+0.0) + ($4+0.0)/60)/($5+0.0);
}

/^tag[ ]+=[ ]+/ { 
  if (pfile != "") { close(pfile); }
  tag = $3; 
  pfile = ("p2c_out_" tag ".txt"); 
  printf "\n" > wfile;
  printf "<!-- tag = %s -->\n", tag > wfile;
  next;
}

/^ref[ ]+=[ ]+/ { 
  ref = $3;
  next;
}

/^[A-Z][A-Za-z_]+[ ]/{ 
  if (NF != 7) { printf "**bug NF\n" > "/dev/stderr"; exit(1); }
  name = $1;
  cSN = compute_coord(0, $2, $3, $4);
  cWE = compute_coord(1, $5, $6, $7);
  # Prints for wikipedia:
  printf "*[[%s, South Sudan|%s]] {{coord|%.4f|N|%.4f|E|display=inline}} <ref name=%s/>\n", \
    name, name, cSN, cWE, ref > wfile;
  # Prints for plotting:
  if (pfile == "") { printf "**bug pfile\n" > "/dev/stderr"; exit(1); }
  printf "%8.4f %8.4f %s %s\n", cWE, cSN, tag, name > pfile; 
  next;
}

function compute_coord(i,odeg,omin,pix) {
  return ((odeg+0.0) + (omin+0.0)/60) + pix*scale[i];
}

// { 
  printf "**bad line «%s»\n", $0 > "/dev/stderr"; exit(1);
}

END {
  if (pfile != "") { close(pfile); }
}
