# backtrack transition probabilities in trained map

BEGIN {
  FS = "/"

  if(level <= 0) level = 2

  for(i = 1; i < level; i++)
    ARGV[ARGC++] = ARGV[ARGC-1]
}

/^[^#]/ {

  if(ARGIND >= 2) {

    n = $1 + 0

    gsub(/[][\|;]/, " ", $3);

    split($3,arr," ")   # => 6 columns n1 n2 n3 a12 a13 sum

    lambda12 = arr[4] + 0
    lambda13 = arr[5] + 0

    l12_2 = lambda12 * lambda12
    l13_2 = lambda13 * lambda13

    h1 = 1 - sqrt(l12_2 + l13_2 + lambda12 * lambda13) # cos(60Deg) theorem
    h2 = 1 - sqrt((t = (1. - lambda12)) * t + l13_2 - t * lambda13)
    h3 = 1 - sqrt((t = (1. - lambda13)) * t + l12_2 - t * lambda12)

    sum = 1. / (h1 + h2 + h3)

    h1 *= sum
    h2 *= sum
    h3 *= sum


#    print arr[1] ":" substr(nna[arr[1]],1,1) ":" (1-h1)/sum " " arr[2] ":" substr(nna[arr[2]],1,1) ":" (1-h2)/sum " " arr[3] ":" substr(nna[arr[3]],1,1) ":" (1-h3)/sum " ", substr(nna[n],3,1)


    # search all per XXX neuron XXX

    n1 = arr[1] + 0
    n2 = arr[2] + 0
    n3 = arr[3] + 0

    for(e in prob) {

      nf = split(e, ee, " ")

      if(nf == ARGIND-1 && ee[nf] == n) {

        prb = prob[e]

        prob[e " " n1] += prb * h1
        prob[e " " n2] += prb * h2
        prob[e " " n3] += prb * h3

      }
    }
  }
  else {                      # use *rebio
    sub(/\r/,"")
    n = split($0,arr, " ")
    prob[arr[n] += 0] = 1
    chr[arr[n]] = substr($0, 1, 1)
  }
}

END {

  for(e in prob) {

    nf = split(e, ee, " ")

    if(nf == level+1) {
      res = "" prob[e] " "
      for(i = 1; i <= nf; i++) res = res "" chr[ee[i]]
      print ee[1], res
    }
  }
}
