#! /bin/bash 
# Last edited on 2017-04-27 20:50:34 by stolfilocal

name="$1"; shift;
level="$1"; shift;
grain="$1"; shift; # Round all lengths to half-multiples of this value.

USAGE=(
  "  This script reads the files \"{name}-{level}-f.dat\" and \"{name}-{level}-t.dat\" created" \
  " by {dm_test_180_discrim.c} and writes to disk a file \"{name}-{level}-discrim.dat\".\n" \
  "\n" \
  "  The file has one line for each" \
  " sub-candidate length {L}, with fields \"{L} {TD(L)} {AD(L)}\", where {TD(L)} is" \
  " the best discrimination threshold for that length and" \
  " {AD(L)} is the the corresponding discrimination accuracy.\n" \
  "\n" \
  "  Let {SF(L)} and {ST(L)} be" \
  " the multisets of scores of false and true candidates, respectively. The" \
  " threshold {TD(L)} is the score value {T} such that the fraction {EF(L,T)} of" \
  " values in {SF(L)} above {T} is equal to the fraction {ET(L,T)} of" \
  " values in {ST(L)} below {T}.  The discrimination accuracy {AD(L)} is" \
  " then the fraction {1-EF(L,TD(L))} or {1-ET(L,TD(L))}.\n" \
)

tmp="/tmp/$$"

ffile="${name}-${level}-f.dat"
tfile="${name}-${level}-t.dat"
sfile="${tmp}.dat"
ofile="${name}-${level}-discrim.dat"

# Combine the files appending '0' and '1' for true and false:
dfiles=( ${ffile} ${tfile} )
for k in 0 1 ; do
  cat ${dfiles[$k]} \
    | gawk \
        -v grain="${grain}" \
        -v k="$k" \
        ' /^[ ]*[0-9]/ {
            nx = $1; ny = $2; sc = $3; 
            L = (nx + ny)/2.0;
            Lr = int(L/grain)*grain + 0.5*grain;
            printf "%12.1f %12.4f %d\n", Lr, sc, k;
          } 
        ' \
    >> ${sfile} 
done

# Sort the files by length and compute the discrimination for each length:
cat ${sfile} \
  | sort -b -k1,1g -k2,2g -k3,3n \
  | compute_discrim.gawk \
  > ${ofile}
  
if [[ -e ${ofile} ]]; then
  plot_threshold.sh ${name} ${level}
  plot_accuracy.sh ${name} ${level}
fi
              
