#! /bin/bash
# Last edited on 2010-06-21 18:10:43 by stolfi

usage="${0##*/} {FILE1}.pgm {FILE2}.pgm > {PLOTFILE}.png"
# Compares two PGM files by plotting pixels of one against the other.

file1="$1"; shift;
file2="$1"; shift;

files=( "${file1}" "${file2}" )

tmp="/tmp/$$"

for i in 0 1 ; do 
  pnmnoraw ${files[${i}]} \
    | tr ' ' '\012' \
    | sed -e '/^$/d' \
    | tail --lines=+4 \
    > ${tmp}-${i}.dat
done

paste ${tmp}-0.dat ${tmp}-1.dat > ${tmp}.dat

cat ${tmp}.dat \
  | gawk \
      ' BEGIN { srw=0; sw=0; } 
        /[0-9]/ {
          r = ($1 + 1)/($2 + 1);
          w = ($1 + $2);
          srw += r*w;
          sw += w;
          next;
        }
        END { printf "%.6f\n", srw/sw; }
      ' \
  > ${tmp}.ratio

ratio=`cat ${tmp}.ratio`

gnuplot <<EOF
  set term png truecolor rounded size 640,600 medium \
    xffffff x000000 x404040 \
    xff0000 x007700 x0055ff
  set output "${tmp}-plot.png"
  set xrange [0:66000]
  set yrange [0:66000]
  plot \
    "${tmp}.dat" using 1:2 with points lt 1 pt 7, \
    (${ratio}*x) with lines
  quit
EOF

cat ${tmp}-plot.png

rm -f ${tmp}-*.dat ${tmp}.dat ${tmp}.ratio  ${tmp}-plot.png  
