#!/bin/bash

echo `date`

##### for target domain in Central America 
latS=-13.5
latN=24.5
lonW=20.5
lonE=53.0
region="eAfrica"

#### SST Domain for Indian Ocean to the Atlantic
lonWeof=50.
lonEeof=340.
latSeof=-20.
latNeof=20.

##### Number of SST and Precip EOFs
numeof=6

#### Model intitial date and forecast period
startmon=5
sznlen=4
ilead=1

obsstartmon=$((ilead + startmon))
obsendmon=$((obsstartmon + sznlen - 1))

currentyr=2026
seasonname="JJAS"

#### For R
testLength=5
trainLength=30
leave3Out=TRUE
runserial=FALSE
obst="MSWEP"
#obst="LOCAL"

#### For ploting -- Change country
mycountry="ETH"  # Costa Rica
yrsstsc=1991
yrsstec=2020
WMOshpfiles="/work/noaa/cpc-s2s/zewdu/shpfiles/WMO_basemap.shp"
WMOshpfiles="/cpc/int_desk/IndianOcean/shpfiles/WMO_basemap.shp"

### For obsevations
firstyr=1991
endyr=2025
monthly=True
isstate=False
obsres=0.25
obsprecip="prec${seasonname}_${firstyr}-${endyr}${obst}.nc"

### Diagnostics
printProb=False
printProbRaw=False
#Diagnostic Domain for Costa Rica
tlats=9.
tlatn=10.
tlonw=40.0 
tlone=41.0 

#### For both R and NCL
###########
szn4mon=False
leadi=$ilead
leadf=$((ilead + sznlen - 1))

allmodelNames=(canesm5 gem5nemo nasa ccsm4 cfsv2 cesm1 ensmean)

###### Select from these
#allprdctors=(MGI ATL3 Nino34 WVG IOD SIOD PCS1 PCS2 PCS3 PCS4 PCS5 PCS6 PCR1 PCR2 PCR3 PCR4 PCR5 PCR6 ALLP_INT)

slctprdctors=(MGI ATL3 Nino34 WVG IOD SIOD PCS1 PCS2 PCS3 PCS4 PCS5 PCS6 PCR1 PCR2 PCR3 PCR4 PCR5 PCR6 ALLP_INT)
allprdctors=$slctprdctors
##############################################

###########################

nprdFirst=$(( ${#slctprdctors[@]} - 1 ))

#######################
join_by_comma() {
  local IFS=","
  echo "$*"
}

quote_items_for_r() {
  local out=()
  for x in "$@"; do
    out+=("\"$x\"")
  done
  local IFS=","
  echo "c(${out[*]})"
}

quote_items_for_ncl() {
  local out=()
  for x in "$@"; do
    out+=("\"$x\"")
  done
  local IFS=","
  echo "(/${out[*]}/)"
}

allmodelNamesR=$(quote_items_for_r "${allmodelNames[@]}")
allmodelNamesNCL=$(quote_items_for_ncl "${allmodelNames[@]}")
slctPrdctrR=$(quote_items_for_r "${slctprdctors[@]}")
allprdctorNCL=$(quote_items_for_ncl "${allprdctors[@]}")
slctprdctrNCL=$(quote_items_for_ncl "${slctprdctors[@]}")

parentDir=$(dirname "$(pwd)") 
workdir="`pwd`"

##########
##### Get observational validation data
#########
cat > paramsObs.ncl <<EOF
startday = 1
iMonth   = $startmon
startmon = $obsstartmon
endmon   = $obsendmon
SEASON   = "$seasonname"
YearS    = $firstyr
YearE    = $endyr
latS     = $latS
latN     = $latN
lonW     = $lonW
lonE     = $lonE
obsT     = "$obst"
monthly  = $monthly
Res      = $obsres
workingDir  = "$workdir"
dataDir     = "$parentDir"
EOF

if [ $obst = "LOCAL" ]; then
 cat paramsObs.ncl templateLocalObs.ncl > obsPrecip.ncl
else
 cat paramsObs.ncl templateObs.ncl > obsPrecip.ncl
fi

#ncl $workdir/obsPrecip.ncl

#######################
#### 2. SST
cat > paramsSST.ncl <<EOF
iMon           = $startmon
YYYY           = $currentyr
SEASON         = "$seasonname"
yrS            = $firstyr
yrE            = $endyr
Leadi          = $leadi
Leadf          = $leadf
latSeof        = $latSeof
latNeof        = $latNeof
lonWeof        = $lonWeof
lonEeof        = $lonEeof
numeof         = $numeof
yrSc           = $yrsstsc
yrEc           = $yrsstec
modelFileNames = $allmodelNamesNCL
workingDir  = "$workdir"
dataDir     = "$parentDir"
EOF

#2 Get NMME SST data
cat paramsSST.ncl templateSSTDownload.ncl > sstDownloadStdz.ncl

#ncl $workdir/sstDownloadStdz.ncl

#######################
#### 3. Get Precip
cat > paramsPrec.ncl <<EOF
iMon           = $startmon
YYYY           = $currentyr
SEASON         = "$seasonname"
yrS            = $firstyr
yrE            = $endyr
Leadi          = $leadi
Leadf          = $leadf
latSeof        = $latS
latNeof        = $latN
lonWeof        = $lonW
lonEeof        = $lonE
numeof         = $numeof
yrSc           = $yrsstsc
yrEc           = $yrsstec
modelFileNames = $allmodelNamesNCL
workingDir  = "$workdir"
dataDir     = "$parentDir"
EOF

#3 Get NMME precip data
cat paramsPrec.ncl templatePrecipDownload.ncl > precDownloadStdz.ncl

#ncl $workdir/precDownloadStdz.ncl

#############################
### 4. R script
####################

cat > params.R <<EOF
iMonth <- $startmon
SznLen <- $sznlen
ThisYr <- $currentyr
SEASON <- "$seasonname"
fileprecnc <- "$obsprecip"
FirstYr <- $firstyr
LastYr <- $endyr
iLead <- $ilead
trainLength <- $trainLength
testLength <- $testLength
Leave3Out <- $leave3Out
RUN_SERIAL <- $runserial
modelFileNames <- $allmodelNamesR
slctPrdctr <- $slctPrdctrR
nprdFirst <- $nprdFirst
workingDir  = "$workdir"
dataDir     = "$parentDir"
EOF

####params.R is sourced inside multiNominalRegression.R
cp ./templateDriver.R  multiNominalRegression.R
#Rscript $workdir/multiNominalRegression.R

echo `date`
