#! /bin/csh -f
# Last edited on 2003-11-04 01:52:17 by stolfi

set usage = "$0"

# Reads a file "p.whites" of pixel values obtained with
# the "xv" eyedropper, and extracts the gamma and white value for 
# each channel from the "p.parms" file.  Plots linearized green 
# and blue against red.

# Set program paths:

set tooldir = "$0"; set tooldir = "${tooldir:h}"
source ${tooldir}/../lib/${PLATFORM}/setpaths.csh 

if ( $#argv != 0 ) then
  echo "usage: ${usage}"; exit 1
endif

set tmp = "/tmp/$$"

if ( ! ( -r p.whites ) ) then
  echo "p.whites not found"; exit 1
endif

if ( -r p.parms ) then
  set t = ( `cat p.parms | grep 'inGamma'` )
  if ( ( $#t != 4 ) || ( "/${t[1]}" != "/-inGamma" ) ) then
    echo "p.parms: bad -inGamma line format"; exit 1
  endif
  set rgamma = ${t[2]}
  set ggamma = ${t[3]}
  set bgamma = ${t[4]}
  set w = ( `cat p.parms | grep 'white'` )
  if ( ( $#w != 6 ) || ( "/${w[1]}" != "/-white" ) || ( "/${w[5]}" != "//" ) ) then
    echo "p.parms: bad -white line format"; exit 1
  endif
  set rmax = ${w[2]}
  set gmax = ${w[3]}
  set bmax = ${w[4]}
  set dmax = ${w[6]}
endif

cat p.whites \
  | tr -s ',=()\[\]' '      ' \
  | gawk '(NF == 12) {printf "%03d %03d %03d\n", $3,$4,$5;}' \
  | sort -n \
  > ${tmp}
  
${gnuplot} \
  -xrm 'gnuplot*line1Color: cyan' -xrm 'gnuplot*line2Color: green' \
  -xrm 'gnuplot*line3Color: purple' -xrm 'gnuplot*line4Color: blue' \
  <<EOF
# set term png small 300 300 \
#   x000000 xffffff x404040 \
#   x00ff00 x77ff77 \
#   x3333ff x9999ff
# set output "whites-plot.png"
set term x11
set xrange [0:300]
set yrange [0:300]
set size ratio -1
plot \
  (((x/255.0)/(${rmax}/(${dmax}+0.01)))**($rgamma/$ggamma))*(${gmax}/(${dmax}+0.01)*255) title "ideal grn" with lines, \
  "${tmp}" using 1:2 title "actual grn" with linespoints, \
  (((x/255.0)/(${rmax}/(${dmax}+0.01)))**($rgamma/$bgamma))*(${bmax}/(${dmax}+0.01)*255) title "ideal blu" with lines, \
  "${tmp}" using 1:3 title "actual blu" with linespoints
pause 300
quit
EOF

# display "whites-plot.png"

/bin/rm ${tmp}