#!/bin/tcsh -f

if ( ! $?GEOSUTIL ) then
      echo " "
      echo Environment variable GEOSUTIL must be defined before use!
      echo Set GEOSUTIL to the directory path of the GEOS_util module
      echo " "
      exit 1
endif

@ nmax = $#argv

# Usage
# -----
if( $nmax == 0 ) then
      echo " "
      echo "Usage:"
      echo "-----"
      echo "quickplot -source   SOURCE_DIRECTORY"
      echo "          -season   SEASON"
      echo "         [-cmpexp   CMPEXP_DIRECTORY]"
      echo "         [-latbeg   LATBEG]"
      echo "         [-latend   LATEND]"
      echo "         [-lonbeg   LONBEG]"
      echo "         [-lonend   LONEND]"
      echo "         [-begdate  BEGDATE]"
      echo "         [-enddate  ENDDATE]"
      echo "         [-cintdiff CINTDIFF]"
      echo "         [-type     TYPE]"
      echo "         [-plots    PLOTS]"
      echo "         [-noplot   NOPLOTS]"
      echo "         [-zlog     ZLOG]"
      echo "         [-plotsdir PLOTSDIR]"
      echo "         [-hist     HISTORY_DIRECTORY]"
      echo "         [-rc       HISTORY.rc]"
      echo "         [-ddf      DDF_FILE]"
      echo "         [-clim     CLIM]"
      echo "         [-taylor   TAYLOR]"
      echo "         [-ana      ANALYSIS]"
      echo "         [-std      STD_DEV ]"
      echo "         [-gradsx   GRADSX]"
      echo "         [-cmpexp_only  CMPEXP_ONLY]"
      echo "         [-cmpops_only  CMPOPS_ONLY]"
      echo " "
      echo "where:    SOURCE_DIRECTORY: is the source directory for experiment"
      echo "                    SEASON: is the season to plot (eg. DJF, JAN)"
      echo "          CMPEXP_DIRECTORY: are the experiment directory(s) to be used for comparison  (Default: None)"
      echo "                    LATBEG: is the beginning Latitude  (Default: -90)"
      echo "                    LATEND: is the    ending Latitude  (Default:  90)"
      echo "                    LONBEG: is the beginning Longitude (Default:   0)"
      echo "                    LONEND: is the    ending Longitude (Default: 360)"
      echo "                   BEGDATE: is the YYYYMM to begin time average  (Default: Begin Date in File)"
      echo "                   ENDDATE: is the YYYYMM to end   time average  (Default: End   Date in File)"
      echo "                  CINTDIFF: optional parameter for dynamic CINT calculation for difference plots  (Default: OFF)"
      echo "                      TYPE: L for Landscape, P for Portrait                 (Default: BOTH)"
      echo "                     PLOTS: prog surf moist turb rad gwd                    (Default: ALL)"
      echo "                      ZLOG: Flag for Zonal Mean ZLOG Option (OFF or ON)     (Default: OFF)"
      echo "                   NOPLOTS: Any plot(s) you wish to skip (useful with ALL)  (Default: NONE)"
      echo "                  PLOTSDIR: is the directory to write plots into            (Default: SOURCE_DIRECTORY/plots)"
      echo "         HISTORY_DIRECTORY: is the directory containing the HISTORY.rc file (Default: SOURCE_DIRECTORY)"
      echo "                HISTORY.rc: is the full path (including filename) "
      echo "                            of the desired rc file to use                   (Default: SOURCE_DIRECTORY/HISTORY.rc)"
      echo "                  DDF_FILE: is the ddf filename (including full path) to use"
      echo "                      CLIM: Logical for using Climatology or Actual Dates   (Default: CLIM     = TRUE)"
      echo "                    TAYLOR: Logical for producing Taylor Plots              (Default: TAYLOR   = TRUE)"
      echo "                  ANALYSIS: Logical for producing Analysis Contour Levels   (Default: ANALYSIS = FALSE)"
      echo "                   STD_DEV: Logical for producing Standard Deviation Plots  (Default: STD_DEV  = FALSE)"
      echo "                    GRADSX: GrADS executable to use for processing          (Default: GRADSX   = gradsnc4)"
      echo "               CMPEXP_ONLY: Logical for producing ONLY CMPEXP plots         (Default: CMPEXP_ONLY = FALSE)"
      echo "               CMPOPS_ONLY: Logical for producing ONLY CMPOPS plots         (Default: CMPOPS_ONLY = FALSE)"
      echo " "
      exit 1
endif


# Set Variables
# -------------
set debug    = false
set type     = ALL
set plots    = ALL
set plotsdir = NULL
set expid    = NULL
set hist     = xxx
set rc       = HISTORY.rc
set clim     = true
set taylor   = true
set analysis = false
set std_dev  = false
set zlog     = OFF
set begdate  = NULL
set enddate  = NULL
set cmpexp   = NULL
set move     = false
set gradsx   = gradsnc4
set noplot   = ""
set latbeg   = -90
set latend   =  90
set lonbeg   =   0
set lonend   = 360
set cintdiff = NULL
set ddffile  = NULL
set seasons  = NULL
set cmpexp_only = FALSE
set cmpops_only = FALSE

# Parse command line
# ------------------

@       n  = 1
while( $n <= $nmax )
       if( "$argv[$n]" == "-source" ) then
                    @ n = $n + 1
             set source = $argv[$n]
       endif
       if( "$argv[$n]" == "-plotsdir" ) then
                    @ n = $n + 1
           set plotsdir = $argv[$n]
       endif
       if( "$argv[$n]" == "-hist"   ) then
                    @ n = $n + 1
             set hist   = $argv[$n]
       endif
       if( "$argv[$n]" == "-rc"     ) then
                    @ n = $n + 1
             set rc     = $argv[$n]
       endif
       if( "$argv[$n]" == "-expid"     ) then
                    @ n = $n + 1
             set expid  = $argv[$n]
       endif
       if( "$argv[$n]" == "-latbeg" | "$argv[$n]" == "-beglat" ) then
                    @ n = $n + 1
             set  latbeg = $argv[$n]
       endif
       if( "$argv[$n]" == "-latend" | "$argv[$n]" == "-endlat" ) then
                    @ n = $n + 1
             set  latend = $argv[$n]
       endif
       if( "$argv[$n]" == "-lonbeg" | "$argv[$n]" == "-beglon" ) then
                    @ n = $n + 1
             set  lonbeg = $argv[$n]
       endif
       if( "$argv[$n]" == "-lonend" | "$argv[$n]" == "-endlon" ) then
                    @ n = $n + 1
             set  lonend = $argv[$n]
       endif
       if( "$argv[$n]" == "-begdate" | "$argv[$n]" == "-datebeg" ) then
                    @ n = $n + 1
             set begdate = $argv[$n]
       endif
       if( "$argv[$n]" == "-enddate" | "$argv[$n]" == "-dateend" ) then
                    @ n = $n + 1
             set enddate = $argv[$n]
       endif
       if( "$argv[$n]" == "-cintdiff"  ) then
                    @ n = $n + 1
            set cintdiff = $argv[$n]
       endif
       if( "$argv[$n]" == "-clim"   ) then
                    @ n = $n + 1
             set clim   = $argv[$n]
       endif
       if( "$argv[$n]" == "-zlog"   ) then
                    @ n = $n + 1
             set  zlog  = $argv[$n]
             set  zlog  = `echo $zlog   | tr "[:lower:]" "[:upper:]"`
             if( $zlog != ON ) set zlog = OFF
       endif
       if( "$argv[$n]" == "-type"   ) then
                    @ n = $n + 1
             set type   = `echo $argv[$n] | tr "[:lower:]" "[:upper:]"`
             if($type  == "1" ) set type = L
             if($type  == "2" ) set type = P
       endif
       if( "$argv[$n]" == "-taylor"   ) then
                    @ n = $n + 1
             set taylor = $argv[$n]
       endif
       if( "$argv[$n]" == "-ddf"   ) then
                    @ n = $n + 1
             set ddffile = $argv[$n]
       endif
       if( "$argv[$n]" == "-gradsx"   ) then
                    @ n = $n + 1
             set gradsx = $argv[$n]
       endif
       if( "$argv[$n]" == "-std"    ) set std_dev  = true
       if( "$argv[$n]" == "-ana"    ) set analysis = true
       if( "$argv[$n]" == "-debug"  ) set debug    = true
       if( "$argv[$n]" == "-move"   ) set move     = true
       if( "$argv[$n]" == "-cmpexp_only" ) set cmpexp_only = TRUE
       if( "$argv[$n]" == "-cmpops_only" ) set cmpops_only = TRUE
       if( "$argv[$n]" == "-cmpexp" ) then
                    @ n = $n + 1
                                      set cmpexp  = ""
                                      set next   = $argv[$n]
                                      set bit    = `echo $next | cut -c1-1`
                                      while( "$bit" != "-" )
                                         set cmpexp = `echo $cmpexp $next`
                                          @   n  = $n + 1
                                         if( $n <= $nmax ) then
                                             set next = $argv[$n]
                                             set bit  = `echo $next | cut -c1-1`
                                         else
                                             set bit  = "-"
                                         endif
                                      end
                                             @ n = $n - 1
       endif
       if( "$argv[$n]" == "-plots"  ) then
                    @ n = $n + 1
                                      set plots  = ""
                                      set next   = $argv[$n]
                                      set bit    = `echo $next | cut -c1-1`
                                      while( "$bit" != "-" )
                                         set plots = `echo $plots $next`
                                          @   n  = $n + 1
                                         if( $n <= $nmax ) then
                                             set next = $argv[$n]
                                             set bit  = `echo $next | cut -c1-1`
                                         else
                                             set bit  = "-"
                                         endif
                                      end
                                             @ n = $n - 1
       endif
       if( "$argv[$n]" == "-noplot"  ) then
                    @ n = $n + 1
                                      set noplot  = ""
                                      set next   = $argv[$n]
                                      set bit    = `echo $next | cut -c1-1`
                                      while( "$bit" != "-" )
                                         set noplot = `echo $noplot $next`
                                          @   n  = $n + 1
                                         if( $n <= $nmax ) then
                                             set next = $argv[$n]
                                             set bit  = `echo $next | cut -c1-1`
                                         else
                                             set bit  = "-"
                                         endif
                                      end
                                             @ n = $n - 1
       endif
       if( "$argv[$n]" == "-season"  ) then
                    @ n = $n + 1
                                      set seasons = ""
                                      set next   = $argv[$n]
                                      set bit    = `echo $next | cut -c1-1`
                                      while( "$bit" != "-" )
                                         set seasons = `echo $seasons $next`
                                          @   n  = $n + 1
                                         if( $n <= $nmax ) then
                                             set next = $argv[$n]
                                             set bit  = `echo $next | cut -c1-1`
                                         else
                                             set bit  = "-"
                                         endif
                                      end
                                             @ n = $n - 1
       endif
     @ n = $n + 1
end

# Prepare Environment
# ---------------------

if( $cmpops_only == TRUE ) set cmpexp_only = TRUE

if( $begdate != NULL ) set clim = false
if( $enddate != NULL ) set clim = false
if( $#seasons > 1    ) set clim = false

setenv SOURCE         $source
setenv CLIM           $clim
setenv TAYLOR         $taylor
setenv ANALYSIS       $analysis
setenv STD_DEV        $std_dev
setenv TBEG           $begdate
setenv TEND           $enddate
setenv GRADSX         $gradsx 
setenv DDFFILE        $ddffile
setenv SEASONS       "$seasons"
setenv CMPEXP_ONLY    $cmpexp_only
setenv CMPOPS_ONLY    $cmpops_only
 
if( $lonbeg < 0 ) then
   @ lonbeg = $lonbeg + 360
   @ lonend = $lonend + 360
endif
setenv LONSENV "$lonbeg $lonend"
setenv LATSENV "$latbeg $latend"

if( $lonbeg != 0 | $lonend != 360 | $latbeg != -90 | $latend != 90 | $cintdiff != NULL ) then
    setenv CINTDIFF ON
endif

if( -e $source/.HOMDIR ) then
    set homdir = `cat $source/.HOMDIR`
else
    set homdir = $source
endif

if( $hist == xxx        ) set hist = $homdir
if( $rc   == HISTORY.rc ) then
    setenv   HISTORYRC    ${hist}/$rc
else
    setenv   HISTORYRC            $rc
endif


# Echo Plotting Environment
# -------------------------
echo " "
echo "plots  = " $plots
echo "season = " $seasons
echo "debug  = " $debug
echo " "
 

# Extract EXPID from HISTORY
# --------------------------
if( $expid == NULL ) set expid = `grep EXPID: $HISTORYRC | cut -d':' -f2`


# Make Output Directory for Plots
# -------------------------------
if( $plotsdir != NULL ) then
      set plots_dir = $plotsdir
else
      set plots_dir = $source/plots
endif
setenv PLOTS_DIR ${plots_dir}
if( ! -e ${plots_dir}/misc ) mkdir -p ${plots_dir}/misc
if ( -e /usr/bin/lfs) then
  /usr/bin/lfs setstripe -c 1 ${plots_dir}
endif


# Run Grads-Based Quickplot Utility
# ---------------------------------
set tmpdirs = ""
foreach plot ($plots)
  echo "Processing $plot of type $type"
  set datetime = `date +%Y%m%d_%H%M%S`
  if( ! -e $plots_dir/$plot.$datetime.$type ) mkdir -p $plots_dir/$plot.$datetime.$type
  cd       $plots_dir/$plot.$datetime.$type
  echo "quickplot $argv" > quickplot.command

# Configure QUICKPLOT to Computing Platform
# -----------------------------------------
$GEOSUTIL/plots/configure
source $plots_dir/$plot.$datetime.$type/.quickplotrc

# Set Default OPS Comparison Experiments
# --------------------------------------
set cmpops = "$VERIFICATION/MERRA2_MEANS:A  \
              $VERIFICATION/ERA5_Monthly:V "

#              $VERIFICATION/MERRA_MEANS:A \
#set cmpops = "$VERIFICATION/ERA5_Monthly:V "
#set cmpops = " "

 set cmpops = `echo $cmpops`

# Update CMPEXP
# -------------
if( $cmpexp[1] != "NULL" ) then
    if( $cmpexp_only == TRUE ) then
         setenv CMPEXP "$cmpexp NULL"
    else
         setenv CMPEXP "$cmpexp $cmpops NULL"
    endif
else
    if( $cmpexp_only == TRUE & $cmpops_only == FALSE ) then
         setenv CMPEXP "$cmpexp"
    else
    echo setenv CMPEXP "$cmpops $cmpexp"
         setenv CMPEXP "$cmpops $cmpexp"
    endif
endif

# ECHO Setup
# ----------
echo "       GRADS = " $GRADS
echo "        ARCH = " `uname`
echo "        HOST = " `hostname`
echo "    GEOSUTIL = " $GEOSUTIL
echo "      SOURCE = " $SOURCE
echo "VERIFICATION = " $VERIFICATION
echo "        CLIM = " $CLIM
echo "      TAYLOR = " $TAYLOR
echo "    ANALYSIS = " $ANALYSIS
echo "     STD_DEV = " $STD_DEV
echo "        PLOT = " $plot
echo "      CMPEXP = " $CMPEXP
echo " CMPEXP_ONLY = " $cmpexp_only
echo " CMPOPS_ONLY = " $cmpops_only
echo " "

set DUMMY = `echo $CMPEXP`
if( "$DUMMY[1]" != "NULL" ) then
  @  NDUMMY = $#DUMMY - 1
  echo "Comparison Experiments: $DUMMY[1]"
  @        N = 2
  while( $N <= $NDUMMY )
  echo "                        $DUMMY[$N]"
  @        N = $N + 1
  end
  echo " "
endif

# Check Format of HISTORY.rc
# --------------------------
   set   test   = `grep COLLECTIONS $HISTORYRC`
   if( "$test" != "" ) then
        /bin/cp $GEOSUTIL/plots/chckhist.new chckhist
   else
        /bin/cp $GEOSUTIL/plots/chckhist.old chckhist
   endif

  set tmpdirs = `echo $tmpdirs $plot.$datetime.$type`

  if( $debug == true ) then

       if($type != P) then
          $GEOSUTIL/plots/landscape.script -expid    $expid     \
                                           -source   $source    \
                                           -plot     $plot      \
                                           -output   $plots_dir \
                                           -geosutil $GEOSUTIL  \
                                           -grads    $GRADS     \
                                           -zlog     $zlog      \
                                           -debug               \
                                           -season   $seasons    
       endif
       if($type != L) then
          $GEOSUTIL/plots/portrait.script  -expid    $expid     \
                                           -source   $source    \
                                           -plot     $plot      \
                                           -output   $plots_dir \
                                           -geosutil $GEOSUTIL  \
                                           -grads    $GRADS     \
                                           -zlog     $zlog      \
                                           -debug               \
                                           -season   $seasons    
       endif

  else

       if($type != P) then
          $GEOSUTIL/plots/landscape.script -expid    $expid     \
                                           -source   $source    \
                                           -plot     $plot      \
                                           -output   $plots_dir \
                                           -geosutil $GEOSUTIL  \
                                           -grads    $GRADS     \
                                           -zlog     $zlog      \
                                           -batch               \
                                           -season   $seasons   &
          sleep 5
       endif
       if($type != L) then
          $GEOSUTIL/plots/portrait.script  -expid    $expid     \
                                           -source   $source    \
                                           -plot     $plot      \
                                           -output   $plots_dir \
                                           -geosutil $GEOSUTIL  \
                                           -grads    $GRADS     \
                                           -zlog     $zlog      \
                                           -batch               \
                                           -season   $seasons   &
          sleep 5
       endif

  endif

end
wait

# Sleep for 3 minutes to ensure all plots are converted
# -----------------------------------------------------
SLEEP:
if( $debug == false ) then
#   sleep 3m
    sleep 10s
else
    sleep 10s
endif

# Reset Environment
# -----------------
cd         $plots_dir
/bin/rm -r $tmpdirs

