#! /bin/bash
# Last edited on 2021-03-05 23:00:26 by jstolfi

# Reads a nine-colum data file as produced by {analyze_egg_shape.py}.
# Plots a selected value against a selected argument.

cmd="$0"; cmd="${cmd##*/}"

imname="$1"; shift   # Egg image name: "egg-a-01", "egg-y-03", etc.
rsmooth="$1"; shift # Smoothing window radius: "0300", "0600", etc.
arg="$1"; shift      # Parameter variable: "arc" or "ang"
val="$1"; shift      # Dependent variable: "cvt", "rad", or "ano".
show=$1; shift       # Display plot if 1, silent if 0

# END COMMAND LINE PARSING
# ----------------------------------------------------------------------

export PATH=".:..:../..:${PATH}"

source process_arg_val.sh

anfile="out/${imname}-sm${rsmooth}-fit.txt"

ptag="${arg}-${val}"  # Tag for plot file.

# Prefix for temporary file names
tmp="/tmp/$$"

hPix=1200
vPix=1200

tfile="${tmp}.png"
export GDFONTPATH="tt-fonts"

# Obtain the total arclength:
lastrec=( `cat ${anfile} | egrep -e '[0-9]' | tail -n 1` )
echo "last line = " "${lastrec[@]}" 1>&2
stot="${lastrec[0]}"
echo "stot = ${stot}" 1>&2

gnuplot <<EOF
  set terminal png truecolor size ${hPix},${vPix} font "arial,18"
  set output "${tfile}"
  set nokey

  stot = ${stot}
  
  # Does not set {xrange,yrange} because variables may not be normalized.
  
  set xlabel "${xlabel}"
  set ylabel "${ylabel}"
  
  arc(dum) = column(1)
  ang(dum) = column(9)
  
  cvt(dum) = column(8)
  rad(dum) = 1/column(8)
  ano(dum) = column(9) - 2*3.1415926*column(1)/stot

  plot \
    "${anfile}" using (${arg}(0)):(${val}(0)) \
      title "${image} ${rsmooth}" with linespoints lt 1 lw 1 pt 7 ps 0.75 lc rgb '#0022cc'

EOF

if [[ -s ${tfile} ]]; then
  pfile="out/${imname}-sm${rsmooth}-${ptag}.png"
  convert ${tfile} -resize '50%' ${pfile}
  if [[ ${show} -ne 0 ]]; then display ${pfile}; fi
  rm ${tfile}
else
  echo "** plot failed" 1>&2 ; exit 1
fi
