#! /bin/csh -f 

set usage = "$0 [-skip NUM] FILE.frq[:STYLE] ... > PLOT.gif"

# STYLE is a digit; 1-4 is red/blue/green/magenta, 5-6 is darkred/darkblue

set skip = ""
while ( ( $#argv > 0 ) && ( "x$1" =~ x-* ) )
  if ( ( $#argv >= 2 ) && ( "x$1" == "x-skip" ) ) then
    set skip = " every :::$2"; shift; shift;
  else
    echo 'unknown option "'"$1"'"'
    echo "usage: ${usage}"; exit 1
  endif
end

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

set tmp = "/tmp/$$"
/bin/rm -f ${tmp}.plt "${tmp}.ppm" "${tmp}.gif"

cat >> ${tmp}.plt <<EOF
set terminal pbm color small
set output "${tmp}.ppm"
set xlabel "rank"
set ylabel "freq"
set lmargin 6
set logscale xy
set xrange [0.80:62.50]
set trange [0.99:50.01]
set yrange [0.0008:0.125]
set noclip one
set ytics mirror ( \
  " 0.1%%" 0.001, " 0.2%%" 0.002, " 0.3%%" 0.003, "" 0.004, " 0.5%%" 0.005, \
  "" 0.006, "0.7%%" 0.007, "" 0.008, "" 0.009, \
  " 1.0%%" 0.010, " 2.0%%" 0.020, " 3.0%%" 0.030, "" 0.040, " 5.0%%" 0.050, \
  "" 0.060, "7.0%%" 0.070, "" 0.080, "" 0.090, \
  "10.0%%" 0.100, "20.0%%" 0.200, "30.0%%" 0.300, "" 0.400, "50.0%%" 0.500, \
  "" 0.600, "70.0%%" 0.700, "" 0.800, "" 0.900, \
  "100.0%%" 1.00 ) 
set xtics mirror ( \
    "1"  1,  "2"  2,  "3"  3, ""  4,  "5"  5, ""  6,  "7"  7, ""  8, ""  9, \
   "10" 10, "20" 20, "30" 30, "" 40, "50" 50, "" 60, "70" 70, "" 80, "" 90, \
  "100" 100 )
# set yrange [0.00:0.11]
# set xrange [-0.01:20.01]
# set xtics 0,1
set size square 0.65,0.82
# set boxwidth 0.75
# set samples 41
plot \
EOF

set ltype = ( 1 3 8 5 7 9 1 3 8 5 7 9 )

@ i = 1
foreach file ( $* )
  if ( "x$file" =~ x*:[0-9] ) then
    set i = `echo ${file} | /bin/sed -e 's/^.*://'`
    set file = `echo ${file} | /bin/sed -e 's/:[^:]*$//'`
  endif
  set name = "${file:r}"
  set style = "with linespoints lt ${ltype[$i]} pt 6 ps 1.5"
  set select = "${skip}"' using ($0+1):2'
  echo '  "'"${file}"'" '"${select}"' title "'"${name}"'" '"${style}"', \' >> ${tmp}.plt
  @ i = $i + 1
end

cat >> ${tmp}.plt <<EOF
  0.320/x title "ideal Zipf" with lines lt 8, \
  0.100/x notitle with lines lt 8, \
  0.032/x notitle with lines lt 8, \
  0.010/x notitle with lines lt 8
quit
EOF

gnuplot < ${tmp}.plt 

if ( ( ! ( -r ${tmp}.ppm ) ) || ( -z ${tmp}.ppm ) ) then 
  rm ${tmp}.ppm; exit 1
endif

ppmtogif < ${tmp}.ppm 
/bin/rm -f ${tmp}.ppm ${tmp}.plt
