#! /bin/csh -f
# Last edited on 2003-09-13 18:30:13 by stolfi

set usage = "$0 [ XMIN XMAX YMIN YMAX ] < INFILE.coords > PLOT.png"

# Reads a file where each line has the form 
#   X Y 
# Plots it.

if ($#argv == 4) then
  set xlo = $1; shift;
  set xhi = $1; shift;
  set ylo = $1; shift;
  set yhi = $1; shift;
endif

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

set raw = 0

set tmp = "/tmp/$$"
set infile = "${tmp}.coords"
set pngfile = "${tmp}.png"

if ( $raw ) then
  cat \
    | egrep -v '^ *[#]' \
    | gawk \
        ' /^ *$/{printf "\n"; next; } \
          /./{ print; } \
        ' \
    > ${infile}
else
  cat \
    | egrep -v '^ *[#]' \
    | gawk \
        ' BEGIN{pi=3.1415926; } \
          /^ *$/{printf "\n"; next; } \
          /./{ \
            x=$1; y=$2; v=(pi/2)*(y/406); \
            s = 0.928*v; \
            h=pi*(x/600)/sqrt(1-s*s/2); \
            v = v * (1.0 + 0.10*cos(h/2)); \
            printf "%4d %4d\n", int(h*1000), int(v*1000); \
          } \
        ' \
    > ${infile}
endif

if ( $?xlo ) then
  set xlim = ( $xlo $xhi )
  set ylim = ( $ylo $yhi )
else
  set xlim = ( `cat ${infile} | gawk 'BEGIN{a=9999;b=-9999;} /./ {v=$1; if(v<a){a=v} if(v>b){b=v}} END{print a,b}'` )
  set ylim = ( `cat ${infile} | gawk 'BEGIN{a=9999;b=-9999;} /./ {v=$2; if(v<a){a=v} if(v>b){b=v}} END{print a,b}'` )
endif

gnuplot <<EOF
set terminal png color medium
set output "${pngfile}"
set nokey
xlo = ${xlim[1]}
xhi = ${xlim[2]}
ylo = ${ylim[1]}
yhi = ${ylim[2]}
set xrange [(xlo-20):(xhi+20)]
set yrange [(ylo-20):(yhi+20)]
set size ratio -1 1.5,1.0
plot \
  "${infile}" using 1:2 with linespoints pointsize 0.5
quit
EOF

if ( ( -r ${pngfile} ) && ( ! ( -z ${pngfile} ) ) ) then
  cat ${pngfile}
  ( xv ${pngfile}; /bin/rm -f ${infile} ${pngfile} ) &
else
  /bin/rm -f ${pngfile}
endif
