# match best substring
# awk -f cfield2crisp.awk reber_617.20.ccfield2 > reber_617.20.crispcfield2
# awk '{printf n=$1" "; for(i=NF;i>1;i--) printf $i; print""}' reber_617.20.crispcfield2 | awk -f isreber.awk


BEGIN {

  T["BP"] = "TV"
  T["BT"] = "SX"
  T["EB"] = "TP"
  T["PS"] = "E"
  T["PT"] = "TV"
  T["PV"] = "PV"
  T["PX"] = "TV"
  T["SE"] = "B"
  T["SS"] = "SX"
  T["SX"] = "SX"
  T["TS"] = "SX"
  T["TT"] = "TV"
  T["TX"] = "SX"
  T["TV"] = "PV"
  T["VE"] = "B"
  T["VP"] = "SX"
  T["VV"] = "E"
  T["XS"] = "E"
  T["XT"] = "TV"
  T["XV"] = "PV" # new ##
  T["XX"] = "TV"


}

{

  str = $2
  le = length(str)
  max = 0
  bestmatch = "*"

  for(p = 1; p < le; p++) {

    if(le - p < max) break  # cannot be improved

    s = substr(str,p,2)

    if(!(s in T)) continue

    r = s

    for(i = p+2; i <= le; i++) {
      if(index(T[s],c = substr(str,i,1)) > 0) {
        r = r c
        s = substr(s,2,1) c
      } else {
        s = "*"
        break
      }
    }

    if((le = length(r)) > max) {
      max = le
      bestmatch = ((p > 1)? "*":"") r ((s=="*")?s:"")
    }
  }

  print $1, bestmatch
}

