#! /bin/bash -eu
# Last edited on 2026-02-15 22:55:30 by stolfi

name="$1"; shift      # Name of input data file (sans "out/" or ".upp").
bin_size="$1"; shift  # Width of histogram bins.
color="$1"; shift     # Bar color, e.g. "#ff0077"

# Reads files "{name}.txt". It must contain one line number per line.
# Plots histogram that data.

tmp="/tmp/$$"

# Counts number of lines

lnu_file="${name}.txt"
nwh_file="${tmp}-${name}.nwh"

echo "=== computing max value in ${lnu_file}" 1>&2 
val_max=$( cat ${lnu_file} | gawk -v max=0 '/[0-9]/{ if ($1 > max) { max = $1} } END { print max }' )
echo "val_max = ${val_max}" 1>&2 

echo "=== computing histogram ${lnu_file} -> ${nwh_file}" 1>&2
make_histogram.gawk -v col=1 -v step=${bin_size} < "${lnu_file}" > "${nwh_file}"

nwh_file="${tmp}-${name}.nwh"
dat_file="${tmp}-${name}.dat"
echo "=== computing plot coords file ${nwh_file} -> ${dat_file}" 1>&2 
cat ${nwh_file} \
  | turn_histogram_into_polygonal_line.gawk \
      -i error_funcs.gawk \
      -v num=1 -v which=0 \
  | gawk '/[0-9]/{ printf "%8.1f %6.1f\n", $1, $2; next} //{ print }' \
  > ${dat_file}

export GDFONTPATH=ttf

temp_plot="${tmp}-big.png"
echo "=== creating plot of ${dat_file}" 1>&2 
gnuplot <<EOF

val_max = ${val_max}
ytitle = "${name}"
bin_size = ${bin_size}

hsize = 2400
vsize = 800

set term png size (hsize),(vsize) font "arial,20" noenhanced
set output "${temp_plot}"

set yrange [-1.0:]
mag = 1
while (mag < 1000000) {
  if (val_max < 10*mag) {
    xmax = 10*mag
    set xtics 0.5*mag; set mxtics 5 
    break
  } else if (val_max < 25*mag) {
    xmax = 25*mag
    set xtics 2.5*mag; set mxtics 5
    break
  } else if (val_max < 50*mag) {
    xmax = 5.0*mag
    set xtics 10*mag; set mxtics 2
    break
  }
  mag = 10*mag
}
set xrange [(-0.02*xmax) : (+1.02*xmax)]
set ytics 5
set mytics 5
set xzeroaxis
set grid ytics
set grid xtics
set xlabel "Line number in file"
set ylabel "Occurrences of 'rk'"

tbs = (bin_size == 1 ? "" : " bin_size = ${bin_size}")
set title ( ytitle . tbs )
set nokey

plot "${dat_file}" using 1:2 notitle with filledcurves lw 2 lc rgb '${color}'

quit
EOF

if [[ -s ${temp_plot} ]]; then
  good_plot="${name}-num-hist.png"
  convert ${temp_plot} -resize '50%' ${good_plot}
  display ${good_plot}
  rm ${tmp}-*
else
  echo "** ${temp_plot} not generated" 1>&2; exit 1
fi
