#! /n/gnu/bin/gawk -f
# Last edited on 2000-02-03 12:11:29 by stolfi

# Reads a stream of element-factored words, extracts core, mantle and
# crust pieces, paired with word type

/^ *$/{next;}
/./{ 
  
  # Delete dummy (empty) factors:

  gsub(/{[_]*}/, "", $0);
  gsub(/[_][_]*/, "", $0);
  
  # Map "ch" and "sh" to "C" and "S" to simplify processing:
  
  gsub(/ch/, "C", $0);
  gsub(/sh/, "S", $0);
  
  # Label and split components: crust/mantle prefixes/suffixes, core.
  
  if ($0 ~ /^[^CSktpfech]*$/) 
    { # Crust-only word:
      $0 = ( "ps-" $0 );
    }
  else if ($0 ~  /^[^ktpf]*$/) 
    { # Empty core, nonempty mantle:
      # Must have at least one element:
      if ($0 !~ /[{].*[CSktpfech].*[}]$/)  { error(("bad format = «" $0 "»")); }

      # Separate and label crust prefix, mantle, and crust suffix:
      $0 = gensub(/[}]([^CSktpfech]*)$/, "}@s-\\1", "g", $0);
      $0 = gensub(/^([^CSktpfech]*)[{]/, "p-\\1@mn-{", "g", $0);
    }
  else
    { # Word has a non-empty core 
      # Must have at least one element:
      if ($0 !~ /[{].*[ktpf].*[}]$/)  { error(("bad format = «" $0 "»")); }

      # Separate and label
      $0 = gensub(/[}]([^ktpf]*)$/, "}@n-{}\\1", "g", $0);
      $0 = gensub(/[}]([^-@CSktpfech]*)$/, "}@s-\\1", "g", $0);

      $0 = gensub(/^([^ktpf]*)[{]/, "\\1{}@c-{", "g", $0);
      $0 = gensub(/^([^-@CSktpfech]*)[{]/, "p-\\1@m-{", "g", $0);
    }
  
  # Break multiple components

  gsub(/[@]/, "\n", $0);
  
  # Delete braces
  
  gsub(/[{}]/, "", $0);

  # Restore "cs" and 'sh":
  
  gsub(/C/, "ch", $0);
  gsub(/S/, "sh", $0);

  print $0;
}

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