#! /bin/bash
# Last edited on 2021-03-06 11:10:13 by jstolfi

# Reads a data file with many curves as created by {combine_graphs.py}.   Plots them 
# on the same plot.

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

egg="$1"; shift       # Egg name: "egg-a", "egg-y", etc.
rsmooth="$1"; shift   # Smoothing radius: "0600", "0300", etc.
arg="$1"; shift       # Argument variable: "arc" or "ang"
val="$1"; shift       # Dependent variable: "cvt", "rad, or "ano"
nc=$1; shift          # Number of curves (not including average).
show=$1; shift        # Display plot if 1, silent if 0

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

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

source process_arg_val.sh

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

hPix=1200
vPix=1200

cfile="out/${egg}-sm${rsmooth}-${arg}-${val}.txt"
tfile="${tmp}.png"   # Temporary plot image.
gfile="${tmp}.gpl"   # Gnuplot commands.

color=(
  '#ff7f7f' #   1.000 0.000 0.000 #ff0000
  '#a9887f' #   0.333 0.067 0.000 #551100
  '#f6a17f' #   0.933 0.267 0.000 #ee4400
  '#88997f' #   0.067 0.200 0.000 #113300
  '#a1b27f' #   0.267 0.400 0.000 #446600
  '#7fa97f' #   0.000 0.333 0.000 #005500
  '#7fc37f' #   0.000 0.533 0.000 #008800
  '#7f99c3' #   0.000 0.200 0.533 #003388
  '#7fa9ff' #   0.000 0.333 1.000 #0055ff
  '#887fbb' #   0.067 0.000 0.467 #110077
  '#997fff' #   0.200 0.000 1.000 #3300ff
  '#a17f88' #   0.267 0.000 0.067 #440011
  '#cc7f99' #   0.600 0.000 0.200 #990033
)

kc=0
printf "plot"  > ${gfile}
sep=' \'

# Plot individual curves:
while [[ ${kc} -lt nc ]]; do
  col=$(( ${kc} + 3 ))
  idc=$(( ${kc} + 1 ))
  printf "%s\n" "${sep}" >> ${gfile}
  printf "  '${cfile}' using 1:%d title 'C%d'" "${col}" "${idc}" >> ${gfile}
  printf " with points lt 1 lw 1 pt 7 ps 0.50 lc rgb '%s'" "${color[${kc}]}" >> ${gfile}
  sep=', \'
  kc=$(( ${kc} + 1 ))
done

# Plot average curve:
printf "%s\n" "${sep}" >> ${gfile}
printf "  '${cfile}' using 1:2 title 'AVG'" >> ${gfile}
printf " with linespoints lt 1 lw 1 pt 7 ps 1.0 lc rgb '#000000'" >> ${gfile}
sep=', \'

# Finish the file:
printf "\n"  >> ${gfile}
# cat ${gfile}

export GDFONTPATH="tt-fonts"

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

  set xrange [-0.002:+2*3.142]; set xtics (3.1415926/4)
  ${setyrange}
  
  set xlabel "${xlabel}"
  set ylabel "${ylabel}"

  load "${gfile}"

EOF

if [[ -s ${tfile} ]]; then
  pfile="${cfile%%.*}.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
