#! /bin/csh -f 
# Last edited on 2004-10-29 04:44:14 by stolfi

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

# Finds the plane that minimizes the mean square deviation 
# of all pixels. Uses {(cr, cg, cb)} as the starting
# guess for the plane's coefficients. If {includeBlack} is TRUE, 
# includes zero pixels in the analysis, otherwise omits them.

set includeBlack = 0; set includeBlackOp = ( )
while ( ( $#argv > 0 ) && ( "/$1" =~ /-[a-z]* ) )
  if ( ( $#argv >= 1 ) && ( "/$1" == "/-includeBlack" ) ) then
    set includeBlack = 1; set includeBlackOp = ( "-includeBlack" ); 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 setcmds = "${tmp}.setplane"

# Add to the prog path some likely locations of tools used
set path = ( tools ../tools ../../tools ../../../tools ${path} )
set foo = `find ${path} -name ppmhist-to-geomview -print | head -1`
set tooldir = "./${foo:h}"

# Compute color histogram:
${tooldir}/check-planarity \
  ${includeBlackOp} \
  "${cr}" "${cg}" "${cb}" "${ct}" "${name}" &

cat ${ppmin} \
  | ppmhist \
  | ${tooldir}/adjust-plane \
      -v includeBlack=${includeBlack} \
      -v cr="${cr}" -v cg="${cg}" -v cb="${cb}" \
  > ${name}.plane
cat ${name}.plane   

cat ${name}.plane \
  | egrep -e 'set *c[rgbt] *[=]' \
  > ${setcmds}
source ${setcmds}

# Compute color histogram:
${tooldir}/check-planarity \
  ${includeBlackOp} \
  "${cr}" "${cg}" "${cb}" "${ct}" "${name}" &

# Cleanup:
rm ${setcmds}