#! /bin/bash
# Last edited on 2021-03-05 20:41:19 by jstolfi

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

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

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

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

anfile="out/${imname}-sm${rsmoothd}-cvt.txt"

tag="adf-by-length"

# 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 "2*pi*s/L"
  set ylabel "theta(s) - 2*pi*s/L"
  
  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${rsmoothd}-${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
