#! /bin/bash
# Last edited on 2023-03-07 10:08:53 by stolfi

# Plots a color path, such as generated by the functions in 
# {frgb_path.h}.
#
# The input file should have columns 
#
#   {index} {z} {R(z)} {G(z)} {B(z)} {Y(z)} {H(z)} {S(z)} {YRB(z)}

dfile="$1"; shift   # File name with color path data.
ifile="$1"; shift   # File with image of color scale, or NONE.
signed="$1"; shift  # 0 for unsigned, 1 for signed.
title="$1"; shift   # Title for whole plot.

echo "${title}" 1>&2

tmp="/tmp/$$"

tfile="${tmp}-t.png"
ufile="${tmp}-u.png"
vfile="${tmp}-v.png"
pfile="${dfile/.txt/_plot.png}"

export GDFONTPATH=${STOLFILOCAL}/ttf

gnuplot << EOF
set term png size 2000,1200 font "arial,14"
set output "${tfile}"

set multiplot layout 2,1 title "${title}"
set nokey
set xrange [((${signed} > 0 ? -1 : 0)-0.01):1.01]
set format y "%7.4f"
set grid ytics mytics lc rgb '#ffaaaa'
# ----------------------------------------------------------------------
# RGB components
set yrange [-0.05:+1.05]
set ytics 0.0, 0.1 mirror
set ylabel "R,G,B"
set y2label "R,G,B"
plot \
  "${dfile}" using 2:3 with lines lc rgb '#ff0000', \
  "${dfile}" using 2:4 with lines lc rgb '#008800', \
  "${dfile}" using 2:5 with lines lc rgb '#2222ff'
# ----------------------------------------------------------------------
# Luminance
set ytics 0.0, 0.1 nomirror
set ylabel "Y,H"
set y2range [-0.05:]
set y2tics 0.0, 0.2
set y2label "S"
plot \
  "${dfile}" using 2:6 title "Y" with lines lc rgb '#222222', \
  "${dfile}" using 2:7 title "H" with lines lc rgb '#008800', \
  "${dfile}" using 2:8 title "S" axis x1y2 with lines lc rgb '#2222ff'
# ----------------------------------------------------------------------
unset multiplot

EOF

if [[ -s ${tfile} ]]; then
  if [[ -s ${ifile} ]]; then
    convert ${tfile} -resize '50%' ${ufile}
    convert ${ifile} -rotate -90 ${vfile}
    convert -append ${ufile} ${vfile} ${pfile}
  else
    convert ${tfile} -resize '50%' ${pfile}
  fi
  display -loop 0 -delay 100x1 ${pfile}
  rm -f ${tfile} ${ufile} ${vfile}
fi
