#!/bin/sh

export LANG=C
export LC_ALL=C

TMP=/tmp/vtsidplot.$$

trap 'bailout "interrupted"' INT QUIT KILL

usage(){
   echo "usage: vtsidplot -m monitor [options] datadir > imagefile" >&2
   echo "" >&2
   echo "options:" >&2
   echo "  -m monitor     Specify a monitor" >&2
   echo "  -T start,end   Time range" >&2
   echo "  -s x,y         Plot size in pixels, default 640,200" >&2
   echo "  -t title       Title for the spectrogram" >&2
   echo "  -g             Display grid" >&2
   echo "  -a count       Average over count raw records" >&2
   echo "  -d count       De-spike spanning count raw records" >&2
   echo "  -h degrees     Apply degrees of hysteresis" >&2
   echo "                 to phases and bearing" >&2
   echo "" >&2
   echo "  -f fields  Comma separated list of fields (default plot all)" >&2
   echo "  -o format  Specify output image format" >&2
   echo "             vtsidplot -o? for available formats" >&2
   echo "" >&2
   exit 1
}

cleanup(){
    [ "$TMP" != "" ] && rm -f $TMP.data $TMP.setup $TMP.size
}

bailout(){
   echo "vtsidplot: $*" >&2
   cleanup
   exit 1
}

TITLE=""
MON=""
TOPT=""
PSIZE=""
HIST=""
AVG=""
GRID=""
DESPIKE=""
FIELDS=""
FORMAT="x11 persist"    # Default terminal type
PO=""

#
#  Parse options
#

OPTS=`getopt -n vtsidplot -o gm:T:t:o:s:h:a:d:f:p:? -- "$@"`
[ $? != 0 ] && usage

eval set -- "$OPTS"

while :
do
   case "$1" in

      -t) TITLE="$2" ; shift 2 ;;

      -m) MON="$2" ; shift 2 ;;

      -T) TOPT="$2" ; shift 2 ;;

      -o) FORMAT="$2" ; shift 2 ;;

      -s) PSIZE="size $2" ; shift 2 ;;

      -h) HIST="-h $2" ; shift 2 ;;

      -a) AVG="-a $2" ; shift 2 ;;

      -d) DESPIKE="-d $2" ; shift 2 ;;

      -f) FIELDS="$2" ; shift 2 ;;

      -p) PO="-p $2" ; shift 2 ;;

      -g) GRID="set grid" ; shift 1 ;;

      -\?) usage ;;

      --) shift ; break ;;

       *) bailout "getopt error" ;;
   esac
done

#
#  Get gnuplot to list available terminals if we got -o?
#

[ "$FORMAT" = "?" ] && {
   echo "set terminal" | gnuplot 2>&1 | sed '/return for more/d'
   exit 0
}

[ "$MON" = "" ] && bailout "must have -m to specify a monitor"

#
#  SID data directory must follow the options
#

[ $# -ne 1 ] && usage
DATADIR=$1

[ "$TITLE" = "" ] && TITLE="$MON $TOPT $DATADIR"

#
#  Handle request -f? to report available fields
#

[ "$FIELDS" = "?" ] && {

   vtsidex -m $MON -T $TOPT -ote -oh -n1 $DATADIR | 
   awk '(NR == 1){
      printf( "fields available:")
      for( i=2; i<=NF; i++) printf( " %s", $i)
      printf( "\n")
   }'
   cleanup
   exit
}

#
#  Extract the data using vtsidex
#

vtsidex -m $MON -T $TOPT $HIST $AVG $DESPIKE $PO -ote -oh -otb $DATADIR |
awk '{
   if( NR == 1)      # Header record
   {
      for( i=2; i<=NF; i++) field_index[$i] = i
      next
   }

   if( NR == 2) T1 = $1 # First timestamp
   T2 = $1              # Last timestamp

   print     # Data records

}END{

   nplot = 0   # Number of fields to plot

   if( request == "")   # No -f option to specify fields, so plot all
   {
      for( field_name in field_index) plot_list[++nplot] = field_name
   }
   else   # -f option supplies a field list
   {
      nplot = split( request, plot_list, "[, ]")
   }

   printf( "size 640,%d\n", nplot * 200) > (TMP ".size")
   setup = TMP ".setup"

   printf( "set multiplot layout %d,1 title %c%s%c\n\n",
            nplot, 39, title, 39) >> setup

   duration = T2 - T1  # Seconds

   if( duration < 86400 * 2)
   {
      printf( "set format x %c%%H:%%M%c\n", 39, 39) >> setup
      printf( "set xlabel %cHH:MM UT%c\n", 39, 39) >> setup
   }
   else
   {
      printf( "set format x %c%%d/%%H%c\n", 39, 39) >> setup
      printf( "set xlabel %cDD/HH UT%c\n", 39, 39) >> setup
   }

   for( n=1; n<=nplot; n++)
   {
      field_name = plot_list[n]

      field_description = field_name
      if( substr( field_name, 1, 1) == "a")
         field_description = sprintf( "Amplitude, channel %d", 
                                       substr( field_name, 2))
      else
      if( substr( field_name, 1, 2) == "cp")
         field_description = sprintf( "Carrier phase, channel %d", 
                                       substr( field_name, 3))
      else
      if( substr( field_name, 1, 2) == "mp")
         field_description = sprintf( "Modulation phase, channel %d", 
                                       substr( field_name, 3))
      else
      if( field_name == "b180")
         field_description = "Apparent bearing, mod 180"
      else
      if( field_name == "b360")
         field_description = "Apparent bearing"

      if( substr( field_name, 1, 1) == "a")
         printf( "set yrange [0:*]\n") >> setup
      else
         printf( "set yrange [*:*]\n") >> setup

      printf( "plot %c%s%c using 1:%d title %c%s%c\n", 
              39, TMP ".data", 39,
              field_index[field_name], 
              39, field_description, 39) >> setup
   }
}' "TMP=$TMP" title="$TITLE" "request=$FIELDS" > $TMP.data

[ $? -ne 0 ] && bailout "error during data extraction"
[ ! -s $TMP.data ] && bailout "no data was found"

[ "$PSIZE" = "" ] && PSIZE=`cat $TMP.size`

echo "
   set terminal $FORMAT $PSIZE
   set xdata time
   set timefmt '%s'
   set style data lines
   $GRID
   set lmargin 13
   `cat $TMP.setup`
   " | gnuplot

cleanup
