#! /bin/csh -fe

set usage = "$0 [-complement] INFILE"

# Reads an .fcv or .cvc file and plots a graph of 
# curvature as a function of sample number.

if ( "x$1" == "x-complement" ) then
  set sgn = "-1"; shift
else
  set sgn = "+1"
endif

set file = "$1"

set ext = "${file:e}"
set name = "${file:r}"
set tmp = "/tmp/$$.plt"

if ( "${ext}" == "fcv" ) then
  cat ${file} \
    | gawk \
        -v sgn="${sgn}" \
        ' /^unit = / { unit=$3; next; } \
          /^[-+ 0-9]/ { printf "%f\n", sgn * unit * $1; next; } \
        '  \
    > ${tmp}
else if ( "${ext}" == "cvc" ) then
  cat ${file} \
    | gawk \
        -v sgn="${sgn}" \
        ' /^unit = / { unit=$3; next; } \
          /^(begin|samples|length|epsilon|delta|end)/ { next; } \
          /^[A-Za-z0]/ {  \
            let = $1;  \
            val = index("zyxwvutsrqponmlkjihgfedcba0ABCDEFGHIJKLMNOPQRSTUVWXYZ", let); \
            if ((val == 0)||(length(let) != 1)) \
              { printf "bad letter (%s)\n", let > "/dev/stderr"; } \
            printf "%2d\n", sgn * (val - 27); next; \
          } \
        '  \
    > ${tmp}
else
  echo "bad extension ${ext}"; exit 1
endif

echo "writing ${name}.ps"

gnuplot <<EOF
set terminal postscript eps monochrome "TimesRoman" 28
set output "${name}.ps"
set size 2,1
set title "${file}"
set nokey
plot "${tmp}" using 1 with lines
quit
EOF

/bin/rm -f ${tmp}

ghostview -openwindows ${name}.ps
