#! /usr/bin/gawk -f
# Last edited on 2004-01-20 01:27:24 by stolfi

BEGIN {
  abort = -1;
  usage = ( \
    "factor-field-general \\\n" \
    "  -f FACTORFUNC.gawk \\\n" \
    "  [ -v inField=NUM ] \\\n" \
    "  [ -v erase=BOOL ] \\\n" \
    "  [ -v outField=NUM ] \\\n" \
    "  < INFILE > OUTFILE" \
  );
  
  # Factors the "inField"th field of INFILE into elements some way,
  # by placing "{}" around each element.
  # If "erase" is set, the input field is erased, otherwise it is
  # preserved. Then inserts the factored word as the "outField"th
  # field.
  #
  # The factorization is defined by a function "factor_text(x)"
  # that must be defined in an included package FACTORFUNC.gawk.
  #
  # The defaults are inField=1, outField=inField, erase=0
  
  if (inField == "") inField = 1;
  if (erase == "") erase = 0;
  if (outField == "") outField = inField;
}

(abort >= 0) { exit abort; }

/^#/ { print; next; }

/./ {
  if (NF < inField) { data_error("not enough input fields"); }
  x = $(inField);
  y = factor_text(x);
  printout(y, outField, inField, erase);
  next;
}  

function printout(mw, ofn, ifn, del,   i)
{
  # prints $0 with "mw" inserted as field "$(ofn)"
  # if "del" is true, deletes field "$(ifn)"
  if (del) 
    { if (NF < ifn) 
        { data_error("not enough input fields\n"); }
      else 
        { for(i=ifn; i<NF-1; i++) { $(i) = $(i+1); } 
          NF--; 
        }
    }
  if (NF < ofn-1) { data_error("not enough output fields\n"); }
  if (ofn == 1)
    { print mw, $0; }
  else if (ofn == NF+1)
    { print $0, mw; }
  else
    { for (i=1;i<ofn;i++) { printf "%s%s", $(i), OFS; }
      printf "%s", mw;
      for (i=ofn;i<=NF;i++) { printf "%s%s", OFS, $(i); }
      printf "\n";
    }
}  

function data_error(msg)
{ 
  printf "line %d: %s\n", NR, msg >> "/dev/stderr";
  abort = 1;
  exit 1;
}

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