#! /bin/bash 
# Last edited on 2009-12-24 16:22:35 by stolfi

cmd="$0"
usage="${cmd##*/} {SKIPX} {SKIPY} {NX} {NY} < {IMAGE}.ppm"
skipx="$1"; shift
skipy="$1"; shift
nx="$1"; shift
ny="$1"; shift

datafile="/tmp/$$.dat"
plotfile="/tmp/$$.png"

cat \
  | pnmcut ${skipx} ${skipy} ${nx} ${ny} \
  | pnmnoraw \
  | sed -e '/[\#]/d' \
  | sed -e '1,3d' \
  | gawk -v nx=${nx} -v ny=${ny} \
      ' BEGIN { n = 0; p = 0; split("",c); m = (nx == 1 ? ny : nx); } 
        /[0-9]/ { 
          for (i = 1; i <= NF; i++) 
            { c[n] = $(i); n++; 
              if (n == 3) 
                { printf "%6d %6d %6d\n", c[0],c[1],c[2]; n = 0; p++;
                  if (p == m) { printf "\n"; p = 0; }
                }
            }
          next;
        }
        END { if (n != 0) { printf "**bug n = %d\n", n > "/dev/stderr"; } }
      ' \
  > ${datafile}
gnuplot <<EOF
  set term png truecolor large \
    xffffff x000000 x404040 \
    xff0000 x007700 x0055ff
  set output "${plotfile}"
  plot "${datafile}" using 0:1 title 'R' with lines lw 2, \
       "${datafile}" using 0:2 title 'G' with lines lw 2, \
       "${datafile}" using 0:3 title 'B' with lines lw 2
  quit
EOF
display ${plotfile}
rm -f ${datafile} ${plotfile}
  
