#! /bin/csh -f 
# Last edited on 2025-05-01 18:28:02 by stolfi

set usage = "$0 [-includeBlack] CR CG CB CT TESTNAME"

set includeBlack = 0
while ( ( $#argv > 0 ) && ( "/$1" =~ /-[a-z]* ) )
  if ( ( $#argv >= 1 ) && ( "/$1" == "/-includeBlack" ) ) then
    set includeBlack = 1; shift
  else
    echo "unrecognized option $1"; exit 1
  endif
end

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

set cr = "$1"; shift;
set cg = "$1"; shift;
set cb = "$1"; shift;
set ct = "$1"; shift;
set name = "$1"; shift;

set ppmin = "${name}.ppm"

set tmp = "/tmp/$$-${name}"

set phist = "${tmp}.phst"
set dhist = "${tmp}.dhst"

# Compute color histogram:
cat ${ppmin} \
   | ppmhist \
   | gawk \
       -v cr="${cr}" -v cg="${cg}" -v cb="${cb}" -v ct="${ct}" \
       -v includeBlack=${includeBlack} \
       ' BEGIN {den = sqrt(cr*cr+cg*cg+cb*cb); } \
         /^ *[0-9]/{ \
           r=$1; g=$2; b=$3; n=$5; \
           if ((! includeBlack) && (r+0 == 0) && (g+0 == 0) && (b+0 == 0)) { next; } \
           d=(cr*r + cg*g + cb*b + ct)/den; \
           printf "%5d %5d %5d %10d %9.1f\n", r,g,b,n,d; \
         } \
       ' \
   | sort -b -k5g \
   > ${phist}
   
# Plot histogram of deviations:
cat ${phist} \
  | gawk \
      -v s=0.50 -v imax=20 \
      ' BEGIN { split("",h); am = 1; } \
        /^ *[0-9]/ { \
          n=$4; d=$5; i=(d<0 ? -int(-d/s+0.5) : int(d/s+0.5)); \
          ai = (i < 0 ? -i : i); if (ai > imax) { next; } \
          h[i] += n; if (ai > am) { am = ai; } \
        } \
        END { \
          for (i=-am; i<= am; i++) \
            { printf "%7.2f %7.2f %7.2f  %7d\n", \
                (i-0.5)*s, i*s, (i+0.5)*s, h[i]; \
            } \
        } \
      ' \
  > ${dhist}
           
gnuplot <<EOF
set term x11
plot "${dhist}" using 2:4 title "${name}" with histeps
pause 60
quit
EOF

# Cleanup:
rm ${phist} ${dhist}
