#! /bin/bash
# Last edited on 2021-03-05 09:22:34 by jstolfi

# Reads a eight-colum data file, plots the difference between
# slope angle and normalized arc length.
# as a function of the tangent angle theta.

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

imname="$1"; shift  # Image name without smoothing radius, directory, tag, extension.
rsmooth="$1"; shift # Smoothing window radius.
show=$1; shift      # Display plot if 1, silent if 0

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

rsmooth=`printf "%04d" "${rsmooth}"`
anfile="out/${imname}-sm${rsmooth}-cvt.txt"

tag="adf-by-theta"

# 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 lins = " "${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

  set xrange [-6.2:+6.2]
  
  stot = ${stot}
  
  set xlabel "theta - 2*pi*s(theta)/L"
  set ylabel "theta"
  
  tnorm(j) = column(j)/(2*3.1415926)
  snorm(i) = column(i)/stot
  dsf(i,j) = tnorm(j)-snorm(i)

  plot \
    "${anfile}" using (snorm(1)):(dsf(1,9)) title "raw" with linespoints lt 1 lw 1 pt 7 ps 0.75 lc rgb '#0022cc'

EOF

if [[ -s ${tfile} ]]; then
  pfile="out/${imname}-sm${rsmooth}-${tag}.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
