# Last edited on 2002-01-16 17:17:42 by stolfi

# Factors a text by placing "{}" around each OKOKOKO element.
# Each "Q" and "K" element with its "I" and "E" complements
# is wrapped with "{}"; the O elements are left undelimited.
# Will provide a dummy element "{_}" if the word has no "q".
#
# To be included in factor-field-general etc.

function factor_text(x,   y,e)
{
  # Decomposes "x" into its OKOKOKO elements. 
  # Assumes "x" is uncapitalized EVA without comments and fillers.
  # EVA spaces and "/" are allowed.

  gsub(/{[^{}]*}/, "", x);
  gsub(/[!]/, "", x);
  if (match(x, /[^-=\/,. *?%a-z]/)) { data_error(("invalid char in word \"" x "\"")); }
  
  # Map "sh", "ch", and "ee" to single letters to simplify the parsing.
  # Note that "eee" groups are paired off from the left end. 
  gsub(/ch/, "C", x);
  gsub(/sh/, "S", x);
  gsub(/ee/, "E", x);

  # Map platformed and half-platformed letters to capitals to simplify the parsing:
  gsub(/ckh/, "K", x);
  gsub(/cth/, "T", x);
  gsub(/cfh/, "F", x);
  gsub(/cph/, "P", x);
  #             
  gsub(/ikh/, "G", x);
  gsub(/ith/, "H", x);
  gsub(/ifh/, "M", x);
  gsub(/iph/, "N", x);
  #
  gsub(/ck/, "U", x);
  gsub(/ct/, "V", x);
  gsub(/cf/, "X", x);
  gsub(/cp/, "Y", x);
  #
  gsub(/ik/, "A", x);
  gsub(/it/, "B", x);
  gsub(/if/, "I", x);
  gsub(/ip/, "J", x);
  
  y = ""; 
  
  while (x != "")
    { # printf "x = [%s]\n", x > "/dev/stderr";
      if (match(x, /^[-=\/,. ]+/))
        { e = substr(x,1,RLENGTH); x = substr(x, RLENGTH+1);
          y = ( y e );
        }
      else
        { # split off initial <q> if any:
          if (match(x, /^[q]/)) 
            { e = substr(x,1,RLENGTH); x = substr(x, RLENGTH+1); }
          else
            { e = "_"; }
          y = ( y "{" e "}");

          while (1)
            { # split off "[aoy]" group
              if (match(x, /^[aoy]+/))
                { e = substr(x,1,RLENGTH); x = substr(x, RLENGTH+1); }
              else
                { e = "_"; }
              y = ( y e );

              # copy next main letter with "i" and "e" complements
              if (match(x, /^([i]+[^-,./=aoyi]|[^-,./=aoyehi][eh]?|[^-,./=aoy])/))
                { e = substr(x,1,RLENGTH); x = substr(x, RLENGTH+1); }
              else
                { break; }
              y = ( y "{" e "}");
            }
        }
    }
  # Unfold letter folding:
  gsub(/A/, "ik", y);
  gsub(/B/, "it", y);
  gsub(/I/, "if", y);
  gsub(/J/, "ip", y);
  #
  gsub(/U/, "ck", y);
  gsub(/V/, "ct", y);
  gsub(/X/, "cf", y);
  gsub(/Y/, "cp", y);
  #
  gsub(/G/, "ikh", y);
  gsub(/H/, "ith", y);
  gsub(/M/, "ifh", y);
  gsub(/N/, "iph", y);
  #
  gsub(/K/, "ckh", y);
  gsub(/T/, "cth", y);
  gsub(/P/, "cph", y);
  gsub(/F/, "cfh", y);
  #
  gsub(/C/, "ch", y);
  gsub(/S/, "sh", y);
  gsub(/E/, "ee", y);

  return y;
}