#!/bin/ksh
# 
#
#	This is OSW Scripts page version.
#       Refer questions to "gs-w osw scripts"
#
#
# **** quick_plot Ver. 1.3 07/20/2009 - lgs & jpn ********
#
#  Change log:
#	Version 1.0  Initial Version
#	Version 1.1: 08/26/2003
#		- Added code from J. Davis to create plotfile if missing
#		- Fixed bug where some plots were hard coded to computed UVs
#       Version 1.2: 07/21/2005
#               - modifed to work with ADAPS 4.5 rdb header
#       Version 1.3: 07/20/2009
#               - fixed bug when multiple data aging exists in plot period - jpn
#       Version 1.4: 03/29/2010
#               - added 7/20 jpn fix to Adaps group option, was missed - wjw
#
# 
# **** Utility to plot NWIS Unit Values data ***************
# 

# Source the NWIS environment
. /usr/opt/etc/nwis.profile
. $NWISHOME/util/nwo_set_nwis_env

User=`whoami`                   # get user
RDIR=`pwd`                      # get run directory
dbno=1                          # edit this line to change database number


date '+ %m/%d/%y' | read today

echo ' '
echo '      **** quick_plot Ver 1.4 - 03/29/2010 ********'
echo ' '
echo '           **********************************'
echo ' '
echo 'This utility will plot unit values from ADAPS using gnuplot'
echo 'for the selected number of days prior to '$today
echo ' '
echo 
echo 'Enter date to begin plot (YYYYMMDD) OR'
echo 'Number of days before today to start plot (0-100): '"\c"
read entnum
numdate=`echo $entnum |wc -c` 

# if you enter a number of days, setting the begin date variable is hard

if test $numdate -le 4
then
echo ''
echo 'You entered' $entnum 'days.'
echo ''
BackDays=$entnum

# Set the current month day and year as end date.
emonth=`date +%m`
eday=`date +%d`
eyear=`date +%Y`
edate=$emonth' '$eday' '$eyear

#initialize beginning date from end date
bmonth=`date +%m`
bday=`date +%d`
byear=`date +%Y`

# Add 0 to month. This is a
# trick to make month an unpadded integer.
bmonth=`expr $bmonth + 0`

# Subtrace n from the current day.
bday=`expr $bday - $BackDays`

# While the day is less than or equal to
# 0, deincrement the month.
while [ $bday -le 0 ]
do
  bmonth=`expr $bmonth - 1`

  # If bmonth is 0 then it is Dec of last year.
  if [ $bmonth -eq 0 ]; then
    byear=`expr $byear - 1`
    bmonth=12
  fi

  # Add the number of days appropriate to the
  # month.
  case $bmonth in
    1|3|5|7|8|10|12) bday=`expr $bday + 31`;;
    4|6|9|11) bday=`expr $bday + 30`;;
    2)
      if [ `expr $byear % 4` -eq 0 ]; then
        if [ `expr $byear % 400` -eq 0 ]; then
          bday=`expr $bday + 29`
        elif [ `expr $byear % 100` -eq 0 ]; then
          bday=`expr $bday + 28`
        else
          bday=`expr $bday + 29`
        fi
      else
        bday=`expr $bday + 28`
      fi
    ;;
  esac
done

  if [ $bmonth -le 9 ]; then
     bmonth='0'$bmonth
  fi

  if [ $bday -le 9 ]; then
     bday='0'$bday
  fi
begin=$byear$bmonth$bday

# if you enter a start date, setting the begin date variable is easy

elif test $numdate -eq 9
then
echo ''
echo 'Begin Date is '$entnum'.'
echo ''
begin=$entnum


else
echo ''
echo 'Invalid entry. Please try again.'
exit
fi

echo 'How many seconds would you like to display each plot? '
echo 'Enter "-1" if you want to <CR> between plots: '"\c"

read PlotTime
echo ''
echo 'Do you want to plot computed (c) or edited (e) values? '"\c"
read Type
case $Type in
    c)
	Typetext='Computed UV'
	;;
    *)
	Typetext='Edited UV'
	;;
esac

date '+ %Y%m%d' | read end
echo ' '
echo
echo 'The utility can use a text file named "plotfile",'
echo 'any ADAPS Group, or you can enter stations and DDs'
echo 'individually from the keyboard.'
echo ' '
echo '  See the ReadMe file for instructions on using the "make_plotfile" utility'
echo '  to create the default "plotfile" for the (f) option.'
echo ' '
echo ' '
echo 'DO YOU WANT TO ENTER STATIONS BY: '
echo ' '
echo 'file (f), ADAPS Group (g) or KEYBOARD (k): '"\c"
read choice
#
if test $choice = "f"
then

# Test to see if plotfile exists, and if not, try to find and run make_plotfile

if [ ! -r "$RDIR/plotfile" ]; then
    echo 'No plotfile found, create one (y/n): '"\c"
    read reply
        if [ "$reply" = "y" ]; then
            if [ -r /usr/opt/nwis/local/util/make_plotfile ]; then
              /usr/opt/nwis/local/util/make_plotfile
            elif [ -r $RDIR/make_plotfile ]; then
              $RDIR/make_plotfile
            else
              echo "\nCan't find make_plotfile script, Aborting...\n"
              exit 1
            fi
        else
          echo "\nQuitting qplot...\n"
           exit 1
        fi
fi

if test $PlotTime -eq -1
then
echo ''
echo '     Hit Return after plot to move to next plot'
echo '(may have to return focus to this window by clicking in window)'
echo ''

else
echo ' '
echo 'EACH PLOT WILL BE DISPLAYED FOR '$PlotTime' SECONDS'
fi

fileno=1
go=1
echo
line=3
while ((go<100))
do
sed -n $line"p" plotfile | read station
if test $station = "end"
then
return
fi
((line=$line+1))
sed -n $line"p" plotfile | read dd
((line=$line+1))
nwts2rdb -oplot$fileno.rdb -n$station -c -d$dd -b$begin -e$end -tuv -s$Type
grep "STATION NAME" plot$fileno.rdb | cut -f2 -d= | sed 's/"/ '$station' - /; s/"//' | read stationid
column DATETIME VALUE <plot$fileno.rdb >plot2$fileno.rdb
#sed -n '18,$p' plot2$fileno.rdb > outfile.rdb
headchg -del <plot2$fileno.rdb >outfile.rdb
rm plot$fileno.rdb
rm plot2$fileno.rdb
echo '# This is File'$fileno > file$fileno
echo '# gnuplot script file' >> file$fileno
echo 'set data style lines' >> file$fileno
echo 'set grid' >> file$fileno
echo 'set xdata time' >> file$fileno
echo 'set ylabel "Stage in feet"' >> file$fileno
echo 'set timefmt "%Y%m%d%H%M%S"' >> file$fileno
echo 'set title ''"'$stationid'"' >> file$fileno
echo 'plot '"'outfile.rdb'"' using 1:2 title '"'$Typetext'"'' with lines >> file$fileno
echo 'pause '$PlotTime >> file$fileno
cp file$fileno gnufile.dat
rm file$fileno
((fileno=$fileno+1))
gnuplot > load 'gnufile.dat'
rm gnufile.dat
rm outfile.rdb
rm load

((go=$go+1))
done;
 
elif test $choice = "g"
then
# work with the Group option

# first get group 
echo ' '
echo '   SELECT GROUP NUMBER FROM LIST BELOW'
echo
\ls /usr/opt/nwis/data/auxdata/groups/database1/*.$User | cut -d'/' -f9 | nl
echo
echo 'Enter station group number to use: '"\c"
read GroupNum
#  

echo ' '
fileno=1
go=1

if test $PlotTime -eq -1
then
echo '           Hit Return to move to the next plot'
echo '(may have to return focus to this window by clicking in window)'
echo ''

else
echo ' '
echo 'EACH PLOT WILL BE DISPLAYED FOR '$PlotTime' SECONDS'
fi

\ls /usr/opt/nwis/data/auxdata/groups/database1/*.$User | nl >grouplist.tmp

LongGroupfile=`grep "[[:space:]]$GroupNum[[:space:]]" grouplist.tmp | cut -f2`
Groupfile=`grep "[[:space:]]$GroupNum[[:space:]]" grouplist.tmp | cut -d'/' -f9`
if [ ! -f "$LongGroupfile" ]
  then
   echo
   echo 'Invalid group number'
   echo
   echo 'Please try again....'
   echo
   exit
fi
cp $LongGroupfile $RDIR/$Groupfile

sed '$ s/SITE/END/g' $Groupfile > $Groupfile".tmp"

line=2
while ((go<100))
do
sed -n $line"p"  $Groupfile".tmp" | awk '{print $3}' | read station
sed -n $line"p"  $Groupfile".tmp" | awk '{print $4}' | read dd
sed -n $line"p"  $Groupfile".tmp" | awk '{print $1}' | read stop

((line=$line+1))

nwts2rdb -oplot$fileno.rdb -n$station -c -d$dd -b$begin -e$end -tuv -s$Type

grep "STATION NAME" plot$fileno.rdb | cut -f2 -d= | sed 's/"/ '$station' - /; s/"//' | read stationid
column DATETIME VALUE <plot$fileno.rdb >plot2$fileno.rdb
#sed -n '18,$p' plot2$fileno.rdb > outfile.rdb
headchg -del <plot2$fileno.rdb >outfile.rdb
rm plot$fileno.rdb
rm plot2$fileno.rdb
echo '# This is File'$fileno > file$fileno
echo '# gnuplot script file' >> file$fileno
echo 'set data style lines' >> file$fileno
echo 'set grid' >> file$fileno
echo 'set xdata time' >> file$fileno
echo 'set ylabel "Stage in feet"' >> file$fileno
echo 'set timefmt "%Y%m%d%H%M%S"' >> file$fileno
echo 'set title ''"'$stationid'"' >> file$fileno

echo 'plot '"'outfile.rdb'"' using 1:2 title '"'$Typetext'"'' with lines >> file$fileno

echo 'pause '$PlotTime >> file$fileno
cp file$fileno gnufile.dat
rm file$fileno
((fileno=$fileno+1))
# echo 'EACH PLOT WILL BE DISPLAYED FOR '$PlotTime' SECONDS'
gnuplot > load 'gnufile.dat'
rm gnufile.dat
rm outfile.rdb
rm load

if test $stop = "/END"
then
break
fi


((go=$go+1))

done;

else
# 
# **** Entering individual stations/DDs from keyboard ***
# 
fileno=1
go=1

echo 
while ((go<99))
do 
echo 'ENTER STATION NUMBER: '"\c"
read station
echo 
echo 'SELECT DD TO PLOT FROM LIST BELOW'
echo
pick_dd -n $station | read dd
echo ' '

# echo $fileno
echo 'STATION: ' $station
echo 'DD: ' $dd
echo 'Begin Date: '$begin
echo 'End Date: '$end
# echo $type

nwts2rdb -oplot$fileno.rdb -n$station -c -d$dd -b$begin -e$end -tuv -s$Type

grep "STATION NAME" plot$fileno.rdb | cut -f2 -d= | sed 's/"/ '$station' - /; s/"//' | read stationid
column DATETIME VALUE <plot$fileno.rdb >plot2$fileno.rdb
#sed -n '18,$p' plot2$fileno.rdb > outfile.rdb
headchg -del < plot2$fileno.rdb > outfile.rdb
rm plot$fileno.rdb
rm plot2$fileno.rdb
echo '# This is File'$fileno > file$fileno
echo '# gnuplot script file' >> file$fileno
echo 'set data style lines' >> file$fileno
echo 'set grid' >> file$fileno
echo 'set xdata time' >> file$fileno
echo 'set ylabel "Stage in feet"' >> file$fileno
echo 'set timefmt "%Y%m%d%H%M%S"' >> file$fileno
echo 'set title ''"'$stationid'"' >> file$fileno
echo 'plot '"'outfile.rdb'"' using 1:2 title '"'$Typetext'"'' >> file$fileno
echo 'pause' $PlotTime >> file$fileno
echo
cp file$fileno gnufile.dat
rm file$fileno
((fileno=$fileno+1))
if test $PlotTime -eq -1
then
echo '       Hit Return after plot'
echo '(may have to return focus to this window by clicking in window)'
fi
if test $PlotTime -gt -1
then
echo 'PLOT WILL BE DISPLAYED FOR' $PlotTime 'SECONDS'
fi
gnuplot > load 'gnufile.dat'
rm gnufile.dat
rm outfile.rdb
rm load
echo 
echo 'HIT <CR> FOR NEXT PLOT OR 99 TO END: '"\c"
read go
((go=$go+1))
done
fi

# Clean up temporary files
# 

rm -f grouplist.tmp
rm -f $Groupfile
rm -f $Groupfile".tmp"
return


