#! /n/gnu/bin/gawk -f
# Last edited on 1998-07-12 05:13:55 by stolfi

BEGIN {
  usage = ( "tuple-value-to-digits \\\n" \
            "  -v order=ORDER \\\n" \
            "  [ -v place=PLACE ] \\\n" \
            "  -v vmin=VMIN \\\n" \
            "  -v vmax=VMAX \\\n" \
            "  < VALFILE > DIGFILE" \
          );

  # The file VALFILE must have entries VALUE WORD where VALUE
  # is a real-value property of the string WORD.
  # The length of all WORDs must be ORDER.
  #
  # This script encodes the VALUE as a digit D in 0..9,
  # by mapping VMIN to 0 and VMAX to 9 with clipping.
  #
  # Then it forms a string DIGS with ORDER digits: if PLACE is given
  # and nonzero, then the PLACEth digit will be D, the rest `0';
  # otherwise all digits will be D. Then writes out a record DIGS WORD

  abort = -1;
  if (order == "") { error("should define \"order\""); } 
  if ((order < 1) || (order > 20)) { error("funny \"order\""); } 
  if ((place == "") || (place == 0))
    { place = 0; } 
  else
    { if ((place < 1) || (place > order)) { error("funny \"place\""); } }
  if (vmin == "") { error("should define \"vmin\""); } 
  if (vmax == "") { error("should define \"vmax\""); } 
}

// {
  if (abort >= 0) { exit(abort); }
  if (NF != 2) { error(("line " NR ": format error")); }
  v = $1;
  w = $2;
  if (length(w) != order) { error(("line " NR ": wrong word length")); }
  d = int(9*(v - vmin)/(vmax - vmin) + 0.5);
  if (d < 0) { d = 0; }
  if (d > 9) { d = 9; }
  if (place == 0)
    { for(i=1;i<=order;i++) { printf "%d", d; } }
  else
    { for(i=1;i<=order;i++) { printf "%d", (i == place ? d : 0); } }
  printf " %s\n", w;
}

function error(msg)
{ printf "%s\n", msg >>  "/dev/stderr";
  abort = 1; exit 0;
}