#!/bin/bash

source allSetParams.sh

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

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`"

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

cat > paramsAllObjective.ncl <<EOF
PRDCTRall      = $slctprdctrNCL
iLead          = $ilead
iMonth         = $startmon
STATE          = $isstate
currentYr      = $currentyr
startmon       = $obsstartmon
SEASON         = "$seasonname"
latS           = $latS
latN           = $latN
lonW           = $lonW
lonE           = $lonE
COUNTRY        = "$mycountry"
Res            = $obsres
printProb      = $printProb
printProbRaw   = $printProbRaw
tlats          = $tlats
tlatn          = $tlatn
tlonw          = $tlonw
tlone          = $tlone
modelFileNames = $allmodelNamesNCL
workingDir     = "$workdir"
dataDir        = "$allcolors"
f1shp          = "$WMOshpfiles"
REGION         = "$region"
obsT           = "$obst"
YearS          = $firstyr
YearE          = $endyr
maskLev        = $masklev
shaderaindry   = $shaderain
useNCLmask     = $UseMask 
RASTER         = $DoRaster
monthly        = "$monthly"
SznLen         = $sznlen
EOF

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

workdir=$(pwd)
ccadat="${workdir}/ccadat/"
echo  $ccadat

cat > myccadat << EOF

CCAdat   = "${ccadat}"
currentDir   = "${workdir}"

EOF


cat myccadat paramsAllObjective.ncl templateShapeFileNames.ncl templateObjectiveFcst.ncl > finalObjectiveFcst.ncl

LoadManager="LINUX"

if [[ $LoadManager == "SLURM" ]]; then

echo "working for $LoadManager"
module purge
module load contrib pyncl
ncl finalObjectiveFcst.ncl

elif [[ $LoadManager == "QSUB" ]]; then
  echo "$LoadManager"


elif [[ $LoadManager == "LINUX" ]]; then
  echo "$LoadManager"

#CONDA_BASE="/cpc/data/software/miniconda"
#source "$CONDA_BASE/bin/activate"
#conda activate rccaenv

# 1. Point explicitly to the micromamba binary in your home folder
export MAMBA_EXE="${HOME}/.local/bin/micromamba"
export MAMBA_ROOT_PREFIX="${HOME}/micromamba"

# 2. Generate the shell hook using the explicit binary path
eval "$($MAMBA_EXE shell hook --shell bash)"

# 3. Now activate will work flawlessly
micromamba activate cpc_rcca_env

ncl finalObjectiveFcst.ncl

fi

