#! /bin/bash -eu
# Last edited on 2026-03-05 12:55:26 by stolfi

ifile="$1"; shift     # Name of data file 0.
title="$1"; shift     # Title for plot.

# Reads file "${ifile}" Each file must contain lines of the form "{LOC}
# {PLEN} {WPOS} {WTYP} {WCOL}" where {LOC} is an arbitrary string,
# {PLEN,WPOS} are fractional numbers near 1.0, {WTYP} is a non-negative
# integerm and {WCOL} is an integer color value Lines with the same
# {LOC} whould be in consecutive positions and should have the same
# {PLEN}.
# 
# Plots each subset with same {LOC} from each file as a gray line of
# length {PLEN} with dots at the positions {WPOS} and size that is a
# function of {WTYP}. Each of these subsets is plotted at a different
# {Y} value.

temp="/tmp/$$"

tfile="${temp}.dat"

cat ${ifile} \
  | plot_pos_file_aux.gawk \
  > ${tfile}

echo -- \
      -i error_funcs.gawk \
      -v yplot=0 \

echo "=== ${tfile} ===" 1>&2
head -n 20 ${tfile} 1>&2
echo "===================" 1>&2

nplots=$( cat ${tfile} | gawk '($4 == -1) { print }' | wc -l )
echo "nplots = ${nplots}" 1>&2 

tmphsize=3200
tmpvsize=$(( 340 + 45*nplots ))

export GDFONTPATH=ttf

tplot="${temp}-big.png"
echo "=== creating plot of ${ifile}" 1>&2 
gnuplot <<EOF
set term png size ${tmphsize},${tmpvsize} font "arial,20" noenhanced
set output "${tplot}"

nplots=${nplots}

set xrange [-2.5:+2.55]
set yrange [-0.50:(nplots-0.50)]
set xtics 0.1
set mxtics 10
set ytics 1.0
set mytics 5
set xzeroaxis
set grid ytics
set grid xtics
set xlabel "Position"
set ylabel "Location"

set title "${title}"

plen(kv,kt) = (column(kt) >= 0 ? 0/0 : column(kv))
xpos(kv,kt) = (column(kt) >= 0 ? column(kv) : 0/0)
ypos(kv) = column(kv)
nonz(kt) = (column(kt) > 0 ? 1 : 0)
psiz(kt) = (column(kt) >= 0 ? 1.5 + 1.5*nonz(kt) : 0)

plot \
  "${tfile}"  using (plen(2,4)):(ypos(3))             notitle with linespoints pt 1 ps 3.0      lw 3 lc rgb '#777777', \
  ""          using (xpos(2,4)):(ypos(3)):(psiz(4)):5 notitle with      points pt 7 ps variable lw 3 lc rgb variable

quit
EOF

if [[ -s ${tplot} ]]; then
  good_plot="${temp}-good.png"
  convert ${tplot} -resize '50%' ${good_plot}
  display ${good_plot}
  cat ${good_plot}
  rm -v ${temp}*.dat ${temp}*.png 
else
  echo "** ${tplot} not generated" 1>&2; exit 1
fi
