#! /bin/bash -eu
# Last edited on 2026-04-25 06:51:08 by stolfi

qmap="$1"; shift      # Type of string map.
size="$1"; shift      # Length of each string in EVA chars.
max_skip="$1"; shift  # Maximum skip between strings

out_dir="res"
ex_dir="work/VoynichNinja/007"

temp="/tmp/$$"

# wc -l ${stats_file_A???} ${stats_file_B???} 1>&2

data_files=()
for kind in 0 1; do
  echo " extracting data for kind = ${kind}..." 1>&2
  data_file="${temp}-stats-k${kind}.txt"
  ent_files=( out/pairs-skip-q${qmap}-n${size}-s*-k${kind}.ent )
  echo "found ${#ent_files[@]} entropy files" 1>&2
  cat ${ent_files[@]} \
    | sort -b -k3,3n \
    > ${data_file}
  data_files+=( ${data_file} )
done

wc -l "${data_files[@]}"

export GDFONTPATH="${HOME}/ttf"

plot_hsize=600
plot_vsize=840
hsize=$(( ${plot_hsize} * 2 ))
vsize=$(( ${plot_vsize} * 2 ))

qt=( "no QO" "with QO" )
qmapx="${qt[${qmap}]}"

echo "raw plot of average length ..." 1>&2
temp_plot_file="${temp}_plot.png"

gnuplot <<EOF
  set term pngcairo size ${hsize},${vsize} linewidth 2.0 font "Arial,30" noenhanced
  set output "${temp_plot_file}"

  set title "string pair correlation - ${qmapx} - length = ${size}"

  set xtics 1
  set nomxtics

  set yrange [-0.001:1.001]
  set ytics 0.2 rotate by 90 center
  set mytics 2

  set grid xtics mxtics lt 1 lc rgb "#44aaff", lt 1 lc rgb "#aaddff"
  set grid ytics mytics lt 1 lc rgb "#44aaff", lt 1 lc rgb "#aaddff"

  set ylabel "relative predictability  (H(W2)-H(W2|W1))/H(W2)" font "Arial,30" offset +2.5,0

  xmax = ${max_skip} + 1

  set xrange [0:xmax]
  set xlabel "distance between strings" font "Arial,30" offset 0,0.3
  set lmargin 6.5; set rmargin 2.0; set bmargin 4.0
  
  val(kj,kp) = column(kj)/column(kp)
  plot \
    "${data_files[0]}" using 3:(val(6,5)) title "mid line" \
      with linespoints pt 7 ps 2.0 \
      lc rgb "#ff0000", \
    "${data_files[1]}" using 3:(val(6,5)) title "across breaks" \
      with linespoints pt 7 ps 2.0 \
      lc rgb "#0033ff"
  quit
EOF

echo "converting plots of average length ..." 1>&2
plot_name="pairs-skip-q${qmap}-n${size}-plot"
plot_file="${out_dir}/${plot_name}.png"
export_plot_file="${ex_dir}/${plot_name}.jpg"
rm -f ${plot_file} ${export_plot_file}
if [[ -s ${temp_plot_file} ]]; then
  convert ${temp_plot_file} -resize '50%' ${plot_file}
  convert ${plot_file} ${export_plot_file}
  ls -l ${export_plot_file}
  display -title '%f' ${plot_file}
else
  echo "** ${temp_plot_file} not created" 1>&2; exit 1
fi

rm -f ${temp}-*
