#! /bin/csh -fx

#SBATCH --partition=singlepe
#SBATCH --time 72:00:00
#SBATCH --job-name=bextdv
#SBATCH --gid=romo
#SBATCH --output=/work/ROMO/users/hou/400.1/16s1_PSAT_v7.10/2.postproc/4.run_bext_dv/bextdv.%j.rlog

#> The following commands output information from the SLURM
#> scheduler to the log files for traceability.
   if ( $SLURM_JOB_ID ) then
      echo
      echo Job ID is $SLURM_JOB_ID
      echo Host is $SLURM_SUBMIT_HOST
      echo Nodefile is $SLURM_JOB_NODELIST
      #> Switch to the working directory. By default,
      #>   SLURM launches processes from your home directory.
      echo Working directory is $SLURM_SUBMIT_DIR
      cd $SLURM_SUBMIT_DIR
   endif

#> Configure the system environment and set up the module capability
   limit stacksize unlimited

set jobID  = ${SLURM_JOB_ID}
set jobDIR = ${SLURM_SUBMIT_DIR}

unset verbose
unalias rm
unalias cp

#> Set the working directories and executable

set VER      = v2

set BASE     = /work/ROMO/users/hou/400.1/16s1_PSAT_v7.10/2.postproc
set DATADIR  = $BASE/outp
set WORKDIR  = $BASE/4.run_bext_dv

set SDATE    = 2016001
set EDATE    = 2016365

set DESC     = camx_v710.GDIT-R6-BART.CAMxRun1.16s1_PSAT_v710.12km.${SDATE}-${EDATE}
set INTXT    = ${DESC}.data.template.txt
set NCTXT    = Natural_Conditions.nc2_4_20.csv
set RETXT    = units_to_facilities.${VER}.txt
set OUTTXT   = ${DESC}.data.template.bext_dv.${VER}.csv

# check if input files exist

if (! (-e $DATADIR/$INTXT) ) then
   echo "$DATADIR/$INTXT must exist "
   exit 
endif

if (! (-e $WORKDIR/$NCTXT) ) then
   echo "$WORKDIR/$NCTXT must exist "
   exit 
endif

if (! (-e $WORKDIR/$RETXT) ) then
   echo "$WORKDIR/$RETXT must exist "
   exit 
endif

#if (! (-e $DATADIR) ) mkdir -p $DATADIR

# Remove any existing output files

if (-e $DATADIR/$OUTTXT) rm $DATADIR/$OUTTXT

setenv INFILE    $DATADIR/$INTXT
setenv NCFILE    $WORKDIR/$NCTXT
setenv REFILE    $WORKDIR/$RETXT
setenv OUTFILE   $DATADIR/$OUTTXT
setenv LOGFILE   $WORKDIR/${DESC}.data.template.bext_dv.${VER}.log

echo $SDATE

R CMD BATCH --no-save --slave calculate_bext_dv.R  $LOGFILE

echo; date; echo

set TODAY = `date +%F | /usr/bin/perl -p -i -e "s/\-//g"`
\mv -vf ${jobDIR}/bextdv.${jobID}.rlog ${jobDIR}/bextdv.${TODAY}.rlog

echo

exit()

