#!/bin/bash

#### Usage : ./newexp exp.param
#### where exp.param is the parameter file



if [ $# -gt 3 ] || [ $# -lt 1 ]; then
    echo "Usage:"
    echo "   ./newexp [paramfile] (option)"
    echo "   Option can be:"
    echo "        -h               just to view all parameters"
  exit
fi

####################################################################
######## PREPARE PATH (PARAM, NEWEXP, LOVECLIM, ASSIMIL...) ########
####################################################################
function checkdeps {
  command -v ifort >/dev/null 2>&1 || { echo >&2 "newexp requires ifort but it's not installed.  Aborting."; exit 1; }
  command -v ncdump >/dev/null 2>&1 || { echo >&2 "newexp requires netcdf but it's not installed.  Aborting."; exit 1; }
  command -v nf-config >/dev/null 2>&1 || { echo >&2 "newexp requires netcdf-fortran but it's not installed.  Aborting."; exit 1; }

  [[ ! -z "${LOVEROOT}" ]] || { echo "Variable LOVEROOT not set"; exit 1; }
  [[ ! -z "${NCDFLOVEDIR}" ]] || { echo "Variable NCDFLOVEDIR not set"; exit 1; }
  [[ ! -z "${NCDFFORTRANDIR}" ]] || { echo "Variable NCDFFORTRANDIR not set"; exit 1; }
  [[ ! -z "${UDULOVEDIR}" ]] || { echo "Variable UDULOVEDIR not set"; exit 1; }
  #[[ ! -z "${NCO_DIR}" ]] || { echo "Variable NCO_DIR not set"; exit 1; }
  #[[ ! -z "${CDO_DIR}" ]] || { echo "Variable CDO_DIR not set"; exit 1; }

  command -v python3 >/dev/null 2>&1 || { echo >&2 "newexp requires python3 but it's not installed.  Aborting."; exit 1; }
}

  #store newexp path
  whereisnewexp=`cd $(dirname $0) && pwd`

  #Check input param file
  masterparamfile=$1
  if [ ${masterparamfile:0:1} == "/" ]; then
    masterparam=$1
  else
    masterparam=$PWD/$1
  fi
  if [ ! -f ${masterparam} ]; then
    echo "Cannot read the paramfile :"
    echo "$PWD/$1"
    exit
  fi

  cd ${whereisnewexp}
  . ${masterparam}

  checkdeps

  #Check Loveclim environment definition
  if [ -z ${LOVEOUTTMP} ]; then
    #echo "Scratchdir: $Scratchdir"
    echo "Path to the working directory undefined!"
    echo "Check your shell startup script to source the 'CONFIG/modules.load' file to add LOVECLIM globals variables to your environment."
    exit
  fi

  #autocomplète les chemins de loveclim
  if [ "${loveclimdir}" == "AUTO" ]; then
    curentPath=`pwd`
    rootdir=`echo ${curentPath} | sed -e "s/RUN.*//"`
    listeofversion=(`ls -X ${rootdir}/LOVECLIM`)
    loveclimdir=${rootdir}LOVECLIM
  fi
  if [ "${Rundir}" == "AUTO" ]; then
    curentPath=`pwd`
    rootdir=`echo ${curentPath} | sed -e "s/\/expdir.*//"`
    Rundir=${rootdir}
  fi


  loveclimdirFormat=`echo "${loveclimdir}" | sed -e "s/\//\\\\\\\\\//g"`
  RundirFormat=`echo "${Rundir}" | sed -e "s/\//\\\\\\\\\//g"`
  ##`cat ${loveclimdir}/RELEASE | awk '{print $1}'`

  #Construct scratch directory
  scratchdir="${LOVEOUTTMP}"


#############################################
############ CONSTRUCT VARIABLE #############
#############################################


  #Calculate simulation time to process
  if [ ${NbRun} == "AUTO" ]; then
    if [ ${lengthInDays} -le 36000 ]; then
      NbRun=1
    else
      NbRun=`python3 -c "from math import ceil; print(int(ceil(${lengthInDays}/(360.*100.))))"`
    fi
  fi

  SecondTotal=`python3 -c "from math import ceil; print(int(ceil((${lengthInDays}/360.)*4*36/${NbRun}.)))"`
  Limit1=$(( 23*3600 )) #24h (un peu moins pour être sur)
  Limit2=$(( 4*24*3600+12*3600 )) #5j (idem)
  if [ ${SecondTotal} -le ${Limit1} ]; then
    NbSecondNeeded=$(( 23*3600+59*60 ))
  elif [ ${SecondTotal} -le ${Limit2} ]; then
    NbSecondNeeded=$(( 4*24*3600+23*3600+59*60 ))
  else
    NbSecondNeeded=${Limit2}
  fi
 
  Minute=`printf "%d\n" $(( ${NbSecondNeeded}/60 ))`
  Second=`printf "%d\n" $(( ${NbSecondNeeded}-60*${Minute} ))`
  Hour=`printf "%d\n" $(( ${Minute}/60 ))`
  Minute=`printf "%d\n" $(( ${Minute}-60*${Hour} ))`



  #Calculate simulation periode


  length_d=$(( ${lengthInDays}%360 ))
  length_y=$(( (${lengthInDays}-${length_d}) / 360))  
  length_m=$(( ${length_y} * 12 ))
  
  startInDays=$(( ${start_y}*360+${start_d} ))
  start_yFormat=`printf "%06d\n" ${start_y}`
  start_dFormat=`printf "%03d\n" ${start_d}`

  endInDays=$(( ${startInDays}+${lengthInDays}-1))
  end_d=$(( (${endInDays}-1)%360+1 )) #le -1 ici c'est parce que contrairement aux durées les dates on besoin de ce -1 parce que le jour de l'année va de 1 à 360 compris
  end_y=$(( (${endInDays}-${end_d})/360))  

  stepInDays=$(( ${lengthInDays}/${NbRun} ))
  step_d=$(( ${stepInDays}%360 ))
  step_y=$(( (${stepInDays}-${step_d}) / 360))  

  icInDays=$(( ${startInDays}-1 )) #si la simu commence en 1850_001 alors les conditions initiale date de 1849_360 (début -1 jour)
  ic_d=$(( (${icInDays}-1)%360+1 ))
  ic_y=$(( (${icInDays}-${ic_d})/360))  
  icstart_yFormat=`printf "ic%06d\n" ${ic_y}`
  icstart_dFormat=`printf "%03d\n" ${ic_d}`

  master_dir="repo"
  machinename=`uname -n`

  if [ ${slurmflag} -eq 1 ]; then
  #mail
  if [ ${mail} == "NO" ]; then
    withmail=0
  else
    withmail=1
    if [ ${mail} == "AUTO" ]; then
      mail=`finger -m $USER | grep @ | awk '{print $NF}' | cut -d"(" -f2 | cut -d")" -f1`
    fi
  fi
  fi

#############################################
############ DISPLAY INFORMATION ############
#############################################

cd ${whereisnewexp}/ref/
${whereisnewexp}/../tools/figlet/figlet -d ${whereisnewexp}/../tools/figlet/fonts ${texp}
cd ${whereisnewexp}
echo "################################################################"
echo "LOVECLIM:"
echo -e "\t${loveclimdir}"
echo "RUN:"
echo -e "\t${Rundir}"
echo -e "\t${NbRun} jobs of $(( ${lengthInDays}/${NbRun} )) days"
[ ${iens} -eq 1 ] && iens=0
[ ${iens} -ne 0 ] && echo -e "\tMulti simulations: ${iens} jobs"
if [ ${slurmflag} -eq 1 ]; then
echo "CLUSTER CONF:"
echo -e "\tTotal time = ${Hour}:${Minute}:${Second}"
echo -e "\tNb CPU = $(( ${ncpu} )) (${ncpu} by NbRun)"
echo -e "\tRAM = ${mem}"
fi
if [ ${debug_mode} -eq 1 ]; then
echo -e "\033[1;31;5mDEBUG MODE = 1\033[0m"
echo -e "\033[1;31mVery huge on the disk (forbiden for simulation longest than 10y)\033[0m"
fi
if [ ${no_comp} -eq 1 ]; then
echo -e "\033[1;31;5mCOMPILATION isn't needed\033[0m"
fi
echo "################################################################"


if [ $# -ge 2 ]; then
  option=$2
if [ ${option} == "h" ] || [ $option == "0" ]; then
    ${Rundir}/expdir/newexp
    exit
  fi
else
    option=0
fi


#############################################
######## CHECK PARAMETER CONSISTANCY ########
#############################################

function checkfile {
  if [ ! -f $1 ] && [ ! -d $1 ]; then
    echo "ERROR :"
    echo "$1 doesn't exists"
    echo "...Check parameter !!"
    exit
  fi
}

if [ $option == "0" ]; then

  echo "Check some parameters :"

  echo -ne "\tLOVECLIM path..."; checkfile ${loveclimdir}; echo "OK"
  if [ ${slurmflag} -eq 1 ]; then
  echo -ne "\tStart date..."; 
  if [ $(( ${start_d}%30 )) -ne 1 ]; then
    echo "You can't start an other day than the first day of a year (1) !!" 
  fi; echo "OK"
  fi
  echo -ne "\tIC..."; checkfile ${Rundir}/expdir/ref/ic/${icstart_yFormat}_${icstart_dFormat}; echo "OK"
  echo -ne "\tScenario..."
  checkfile ${loveclimdir}/scenario/${scenGHG}/GHG.dat
  checkfile ${loveclimdir}/scenario/${scenGHG}/OZONE.dat
  checkfile ${loveclimdir}/scenario/${scenGHG}/SUL.nc
  checkfile ${loveclimdir}/scenario/${scenTSI}/TSI.dat
  checkfile ${loveclimdir}/scenario/${scenVeget}/VEGET.nc
  checkfile ${loveclimdir}/scenario/${scenTOPO}/berg.nc
  if [ "${scenVolc}" != "NONE" ] && [ ${vol} -eq 1 ]; then checkfile ${loveclimdir}/scenario/${scenVolc}/VOLC.dat; fi
  if [ "${scenIMSK}" != "NONE" ] && [ ${imsk} -eq 1 ]; then checkfile ${loveclimdir}/scenario/$scenIMSK/icemask.nc; fi
  if [ "${scenFWF}" != "NONE" ] && [ ${fwf} -eq 1 ]; then
   checkfile ${loveclimdir}/scenario/${scenFWF}/FWF_WAIS.nc
   checkfile ${loveclimdir}/scenario/${scenFWF}/FWF_HUD.nc
   checkfile ${loveclimdir}/scenario/${scenFWF}/FWF_LAW.nc
   #checkfile ${loveclimdir}/scenario/$scenfwf/FWF_ARC.nc
   #checkfile ${loveclimdir}/scenario/$scenfwf/FWF_FIS.nc
   #checkfile ${loveclimdir}/scenario/$scenfwf/FWF_GOM.nc
   #checkfile ${loveclimdir}/scenario/$scenfwf/FWF_MED.nc
   #checkfile ${loveclimdir}/scenario/$scenfwf/FWF_NAT.nc
   #checkfile ${loveclimdir}/scenario/$scenfwf/FWF_OUT.nc
   #checkfile ${loveclimdir}/scenario/$scenfwf/FWF_PAC.nc
  fi
  echo "OK"

  echo -ne "\tExperiment path..."
  if [ -d ${Rundir}/expdir/${texp} ]; then
    echo "directory ${texp} exists but you can overwrite an experiment"
    exit
  fi
  echo "OK"

  if [ ${iso} -eq 1 ]; then echo -ne "\tISOTOPE tracer..."; echo "ACTIVATED"; fi
  if [ ${cfc} -eq 1 ]; then echo -ne "\tCFC..."; echo "ACTIVATED"; fi
  if [ ${tobi} -eq 1 ]; then echo -ne "\tTOBI..."; echo "ACTIVATED"; fi
  if [ ${lgm} -eq 1 ]; then echo -ne "\tLGM..."; echo "ACTIVATED"; fi
  if [ ${icy} -ne 0 ]; then echo -ne "\tICY..."; echo "ACTIVATED with ${icy}"; fi
  if [ ${lgm} -eq 1 ] && [ ${icy} -ne 0 ]; then echo -ne "\tICY and LGM can't be together..."; echo "KO"; exit; fi
  if [ ${kata} -ne 0 ]; then echo -ne "\tKATA..."; echo "ACTIVATED with ${kata}"; fi
  if [ ${abel} -eq 1 ]; then echo -ne "\tABEL..."; echo "ACTIVATED"; fi
  if [ ${fwf} -eq 1 ]; then echo -ne "\tFWF..."; echo "ACTIVATED"; fi
  if [ ${cloud} -eq 1 ]; then echo -ne "\tCLOUD..."; echo "ACTIVATED"; fi
  if [ ${loch} -eq 1 ]; then echo -ne "\tLOCH..."; echo "ACTIVATED"; fi
  if [ ${ism} -eq 1 ]; then echo -ne "\tISM..."; echo "ACTIVATED"; fi
  #if [ ${ensemble} -eq 1 ]; then echo -ne "\tENSEMBLE..."; echo "ACTIVATED"; fi


  echo "################################################################"

#############################################
######## CREATE EXPERIMENT DIRECTORY ########
#############################################
  
  echo "Create directory ${texp}";
  mkdir ${texp}
  cd ${texp}

  #Copy the reference directory
  rsync -aqz --exclude='make*' --exclude='comp_*' --exclude='ic' --exclude='.svn' --exclude="*.flf" --exclude="save_loveclim" --exclude="rsyncR" ../ref/* .
  cd repo


#############################################
############# CREATE RUN.PARAM ##############
#############################################

  echo "Create run.param"
  sed -i "\
  s/EXPNAME/${texp}/g;\
  s/HYSTER/${hyst}/g;\
  s/VCOR/${vcor}/g;\
  s/BERING/${bering}/g;\
  s/TXIFCB/${txifcb}/g;\
  s/TXIFCU/${txifcu}/g;\
  s/AVKB/${avkb}/g;\
  s/ISODIFFAI/${ai}/g;\
  s/AITD/${aitd}/g;\
  s/CLIO_NSKIPD/${nsav}/g;\
  s/LOTUR/${lotur}/g" run.param

##############################################
########## CREATE OUTP_OCEAN.PARAM ###########
##############################################

  echo "Create outp_ocean.param"
  sed -i "\
  s/MAXTIM1/${length_m}/g;\
  s/DAILYMEANOVERPERIOD/${daily_mean_over_period}/g;\
  s/MAXTIM2/${length_y}/g" outp_ocean.param

##############################################
########## CREATE OUTP_ATMOS.PARAM ###########
##############################################

  echo "Create outp_atmos.param"
  sed -i "\
  s/DAILYMEANOVERPERIOD/${daily_mean_over_period}/g" outp_atmos.param

#############################################
############# CREATE ISM.PARAM ##############
#############################################

  #Pour ISM: le start est le temps de 
  #debut de TOUTE l'experience
  if [ ${ism} -eq 1 ]; then 
    echo "Create ism.param"
    sed -i "s,START,${start_y},g" ism.param
  else
    rm ism.param
  fi

#############################################
############# CREATE EMIC.PARAM #############
#############################################

  echo "Create emic.param"
  sed -i "\
  s/vec/${vecode}/g;\
  s/icb/${icebergs}/g;\
  s/aism/${aism}/g;\
  s/gism/${gism}/g;\
  s/loch/${loch}/g;\
  s/rad/${radiative}/g;\
  s/fer/${fertilisation}/g" emic.param


#############################################
############# CREATE COMPIL.PARAM ###########
#############################################

  echo "Create compil.param"
  if [ ${iscy} -eq 1 ] && [ ${transientICY} -eq 1 ]; then icy=3; fi
  if [ ${iscy} -eq 2 ] && [ ${transientICY} -eq 1 ]; then icy=4; fi
  sed -i "\
  s/tobi/${tobi}/g;\
  s/iso/${iso}/g;\
  s/cfc/${cfc}/g;\
  s/fwf/${fwf}/g;\
  s/cloud/${cloud}/g;\
  s/lgm/${lgm}/g;\
  s/s_icy/${start_y}/g;\
  s/f_icy/${ref_icy}/g;\
  s/icy/${icy}/g;\
  s/loch/${loch}/g;\
  s/obin/${obinloch}/g;\
  s/ensemble/${ensemble}/g;\
  s/ism/${ism}/g;\
  s/abel/${abel}/g;\
  s/kata/${kata}/g" compil.param

#############################################
###########CREATE FWF.PARAM ############# 
#############################################

  if [ ${fwf} -eq 1 ]; then

    echo "Create FWF.param"
    sed -i "\
    s/SCENFWF/${scenFWF}/g;\
    s/ACTFWF/${fwf}/g;\
    s/MUFWF/${muFWF}/g;\
    s/SIGFWF/${sigFWF}/g;\
    s/EPSFWF/${epsFWF}/g;\
    s/FREQFWF/${freqFWF}/g" FWF.param

  else
    rm FWF.param
  fi

#############################################
####### CREATE NAMELIST-ECBILT.PARAM ########
#############################################

  echo "Create namelist-ecbilt.param"
  iiens=${iens}
  [ ${iens} -ne 0 ] && iiens=1
  if [ "${scenVolc}" == "NONE" ] && [ ${sigmaRandom} -eq 0 ]; then
    vol=0
  fi
  sed -i "\
  s/ICEL/${cel}/g;\
  s/ECCF/${eccf}/g;\
  s/OBLF/${oblf}/g;\
  s/OMWEBF/${omwebf}/g;\
  s/IGHG2S/${ghg2s}/g;\
  s/IGHG/${ghg}/g;\
  s/ITSI/${tsi}/g;\
  s/IVOL/${vol}/g;\
  s/ISUL/${sul}/g;\
  s/IO3/${o3}/g;\
  s/IENS/${iiens}/g;\
  s/AMPWIR/${ampwir}/g;\
  s/INITDATE/${initdate}/g;\
  s/ampeqir/${AMPEQIR}/g;\
  s/expir/${EXPIR}/g;\
  s/hproftrop/${HPROFTROP}/g;\
  s/hprofeq/${HPROFEQ}/g;\
  s/hprofw/${HPROFW}/g;\
  s/hprofan/${HPROFAN}/g;\
  s/h2profan/${HPROFAN2}/g;\
  s/ampanir/${AMPANIR}/g;\
  s/a2mpanir/${AMPANIR2}/g;\
  s/CWDRAG/${cwdrag}/g;\
  s/RRDEF1/${rrdef1}/g;\
  s/RRDEF2/${rrdef2}/g;\
  s/ALBOCEF/${albocef}/g;\
  s/CORAN/${corAN}/g;\
  s/CORAS/${corAS}/g;\
  s/RELHMAX/${relhmax}/g;\
  s/ALBIN/${albin}/g;\
  s/ALBIS/${albis}/g;\
  s/ALBICE/${albice}/g;\
  s/ALPHDI/${alphdi}/g;\
  s/ALPHD/${alphd}/g;\
  s/ALPHS/${alphs}/g;\
  s/CGREN/${cgren}/g;\
  s/BUP/${bup}/g" namelist-ecbilt


#############################################
############## CREATE VEGET.PAR #############
#############################################

  echo "Create veget.par"
  sed -i "\
  s/EXPNAME/${texp}/g;\
  s/ENGR/${engr}/g;\
  s/ENTR/${entr}/g;\
  s/IVEG/${veg}/g;\
  s/FVEG/${vegflux}/g" veget.par


##### LOCH
#############################################
############ CREATE runloch.dat #############
#############################################

  if [ ${loch} -eq 1 ]; then

    echo "Create runloch.dat"
    sed -i "\
    s/latmo/${LATMO}/g;\
    s/levol/${CO2_evolue}/g;\
    s/lforce/${emissions}/g;\
    s/file_conc/${fileconc}/g;\
    s/file_emissFF/${fileff}/g;\
    s/file_emissDEF/${filedef}/g;\
    s/file_dC13DEF/${filedc13def}/g;\
    s/file_dC13FF/${filedc13ff}/g;\
    s/file_dC13/${filedc13}/g;\
    s/file_DC14DEF/${fileDC14def}/g;\
    s/file_DC14FF/${fileDC14ff}/g;\
    s/file_DC14/${fileDC14}/g;\
    s/lcosmic/${lcosmic}/g;\
    s/lriver/${lriver}/g;\
    s/lage/${LAGE}/g;\
    s/dateCO2/${dateco2}/g" runloch.dat

    echo "Create outp_loch.param"
    sed -i "\
    s/MAXTIM1/${length_m}/g;\
    s/MAXTIM2/${length_y}/g" outp_loch.param

    ## horloge de Loch
    echo "Create tploch.LOLD"
    sed -i "\
    s/YEAR1_loch/${YEAR1_loch}/g" tploch.LOLD

#############################################
############ CREATE LOGLOCH.par #############
#############################################

    echo "Create LOGLOCH.par"
    sed -i "\
     s/XKWA/${XKWA}/g;\
     s/PHYMAX/${PHYMAX}/g;\
     s/ZDIATOM/${ZDIATOM}/g;\
     s/ZOTHERS/${ZOTHERS}/g;\
     s/ARAGON/${ARAGON}/g;\
     s/PRESIL/${PRESIL}/g;\
     s/PRECMI/${PRECMI}/g;\
     s/FRPREC/${FRPREC}/g;\
     s/PRECIT/${PRECIT}/g;\
     s/PRECSA/${PRECSA}/g" LOGLOCH.par

  else
    rm runloch.dat LOGLOCH.par SEAPIG.par tploch.LOLD outp_loch.param
  fi

#############################################
############# CREATE SENS_G.PAR #############
#############################################

  if [ ${ism} -eq 1 ]; then

    echo "Create sens_G.par"
    sed -i "\
    s/ANEWG/${anewg}/g;\
    s/ASL/${asl}/g;\
    s/SIGMA/${sigmag}/g;\
    s/DDFS/${ddfsg}/g;\
    s/DDFI/${ddfig}/g;\
    s/CALVCOR/${calvcor}/g" sens_G.par


#############################################
############# CREATE SENS_A.PAR #############
#############################################

    echo "Create sens_A.par"
    sed -i "\
    s/C1/${c1}/g;\
    s/C2/${c2}/g;\
    s/C3/${c3}/g;\
    s/SIGMA/${sigmaa}/g;\
    s/DDFS/${ddfsa}/g;\
    s/DDFI/${ddfia}/g" sens_A.par

  else
    rm sens_G.par sens_A.par

  fi
  
#############################################
############### COPY IC?????? ###############
#############################################

  echo "Copy ${icstart_yFormat}_${icstart_dFormat}";
  commande="cd ${Rundir}/expdir/$texp"
  exp=$master_dir
  commande="${commande}; cp -rf ../ref/ic/${icstart_yFormat}_${icstart_dFormat} $master_dir/"
  commande="${commande}; echo 1 > $exp/${icstart_yFormat}_${icstart_dFormat}/weight.dat"
  eval ${commande}
#  nbtry=0
#  ssh storage01 "${commande}"
#  while [ $? -ne 0 ] && [ ${nbtry} -lt 20 ]
#  do
#    nbtry=$(( ${nbtry}+1 ))
#    echo "Try ${nbtry}/20, next in 10 sec"
#    sleep 10
#    ssh storage01 "${commande}"
#  done

#  wait

#############################################
# Horloge de LOCH
#############################################
 
  if [ ${loch} -eq 1 ]; then
    cp $master_dir/tploch.LOLD $master_dir/${icstart_yFormat}_${icstart_dFormat}/.
    #echo 'VERS:',$master_dir/${icstart_yFormat}_${icstart_dFormat}/
  fi
  
#############################################
########## COPY MASTER PARAM FILE ###########
#############################################

  echo "Copy $masterparam";
  cp -f $masterparam ${Rundir}/expdir/$texp/$texp.param
  sed -i "\
  s/loveclimdir=AUTO/loveclimdir=${loveclimdirFormat}/g;\
  s/mail=AUTO/mail=${mail}/g;\
  s/NbRun=AUTO/NbRun=${NbRun}/g;\
  s/Rundir=AUTO/Rundir=${RundirFormat}/g;" ${Rundir}/expdir/$texp/$texp.param


#############################################
######### CREATE RUN FILES : SUB.? ##########
#############################################

  cd ${Rundir}/expdir/$texp

  echo "Create raw sub"
  sed -i "\
  s,{TEXP},${texp},g;\
  s,{SCRATCHDIR},${scratchdir},g;\
  s,{LOVECLIMDIR},${loveclimdir},g;\
  s,{RUNDIR},${Rundir},g;\
  s,{ASSIMETHODE},${Assimethode},g;\
  s,{SAVINGHOST},${SavingHost},g;\
  s,{COSTBIN},${costbin},g;\
  s,{NUMYEAR},${step_y},g;\
  s,{NUMDAY},${step_d},g;\
  s,{NUMSAVEY},${step_y},g;\
  s,{NUMSAVED},${step_d},g;\
  s,{MASTERDIR},${master_dir},g;\
  s,{SCENGHG},${scenGHG},g;\
  s,{SCENTSI},${scenTSI},g;\
  s,{SCENVOLC},${scenVolc},g;\
  s,{SCENFWF},${scenFWF},g;\
  s,{SCENTOPO},${scenTOPO},g;\
  s,{SCENIMSK},${scenIMSK},g;\
  s,{SCENICY},${scenICY},g;\
  s,{SCENVEGET},${scenVeget},g" sub.sc


#############################################
########## COPY POSTRAITE.SC      ###########
#############################################

  echo "Create postraite.sc"
  sed -i "\
  s,{RUNDIR},${Rundir},g;\
  s,{NCODIR},${ncodir},g;\
  s,{CDODIR},${cdodir},g;" postraite.sc

#############################################
######### CREATE LAUNCH_RPOST  ##############
#############################################

  echo "Create launch_rpost"
  launchname="launch_rpost"
  echo "#!/bin/bash"                                                > ${launchname}
  if [ ${slurmflag} -eq 1 ]; then
  echo "###############################################################################" >> ${launchname}
  echo "#                              RUN LOVECLIM                                    " >> ${launchname}
  echo "###############################################################################" >> ${launchname}
  echo "# Define the job name"                                                           >> ${launchname}
  echo "#SBATCH --job-name={postname}"                                                   >> ${launchname}
  echo "#"                                                                               >> ${launchname}
  if [ ${withmail} -eq 1 ]; then
    echo "# Advised: your Email here, for job notification"                              >> ${launchname}
    echo "#SBATCH --mail-user=${mail}"                                                   >> ${launchname}
    echo "#SBATCH --mail-type=ALL"                                                       >> ${launchname}
    echo "#     (ALL = BEGIN, END, FAIL, REQUEUE)"                                       >> ${launchname}
    echo "#"                                                                             >> ${launchname}
  fi
  echo "# Set a pattern for the output file."                                            >> ${launchname}
  echo "#SBATCH --output=${Rundir}/expdir/$texp/log/{postname}.%j"                       >> ${launchname}
  echo "#"                                                                               >> ${launchname}
  echo "###############################################################################" >> ${launchname}
  echo "# The requested run-time"                                                        >> ${launchname}
  echo "#"                                                                               >> ${launchname}
  echo "#SBATCH --time=0-${Hour}:${Minute}:${Second}"                                    >> ${launchname}
  echo "#"                                                                               >> ${launchname}
  echo "###############################################################################" >> ${launchname}
  echo "# Requested number of cores. Choose either of, or both of"                       >> ${launchname}
  echo "#"                                                                               >> ${launchname}
  echo "#SBATCH --ntasks=${ncpu}"                                                        >> ${launchname}
  echo "##SBATCH --exclusive"                                                            >> ${launchname}
  echo "##SBATCH --cpus-per-task=1"                                                      >> ${launchname}
  echo "##SBATCH --ntasks-per-node=1"                                                    >> ${launchname}
  echo "#"                                                                               >> ${launchname}
  echo "###############################################################################" >> ${launchname}
  echo "# Requested memory for each core"                                                >> ${launchname}
  echo "#"                                                                               >> ${launchname}
  echo "#SBATCH --mem-per-cpu=${mem}"                                                    >> ${launchname}
  echo "###############################################################################" >> ${launchname}
  echo ""                                                                                >> ${launchname}
  echo "ulimit -s unlimited"                                                             >> ${launchname}
  echo "#export MALLOC_CHECK_=0"                                                         >> ${launchname}
  echo ""                                                                                >> ${launchname}
  echo "###############################################################################" >> ${launchname}
  echo ""                                                                                >> ${launchname}
  else
  echo "#$ -o ${Rundir}/expdir/$texp/log/{postname}.\$JOB_ID"      >> ${launchname}
  echo "# ---------------------------"                             >> ${launchname}
  fi

  timefin=$(( ${start_y}+${length_y} ))
  echo "path_post=${Rundir}/expdir/${texp}"                        >> ${launchname}
  echo "iatmos=1"                                                  >> ${launchname}
  echo "iocean=1"                                                  >> ${launchname}
  echo "iveget=1"                                                  >> ${launchname}
  echo "iother=1"                                                  >> ${launchname}
  echo "\${path_post}/{EXP}/postraite.sc ${texp} ${start_y} ${timefin} ${step_y} \${iatmos} \${iocean} \${ioceanevo} \${iveget} >> \${path_post}/log/{postname}.log 2>&1">> ${launchname}

fi #option

chmod 755 ${launchname}


#############################################
############ CREATE LAUNCH_R?    ############
#############################################
iiens=${iens}
if [ ${option} == "h" ] || [ $option == "0" ]; then
[ ${iens} -eq 0 ] && iiens=1
numens=1
while [ ${numens} -le ${iiens} ] ; do

  master_dir=${exp}${numens}
  [ ${iens} -eq 0 ] && master_dir=${exp}
  cd ${Rundir}/expdir/${texp}
  
  stepstart=1
  stepsend=${NbRun}
  
  for step in `seq ${stepstart} 1 ${stepsend}`
  do

    if [ ${step} -eq 1 ]; then
      optcmp=1
    else
      optcmp=3
    fi

    if [ ${no_comp} -eq 1 ]; then
      optcmp=3
    fi

    launchname="launch_r${step}"
    [ ${iens} -ne 0 ] && launchname="launch_r${numens}${step}"
    begtimeInDays=$(( ${startInDays}+${stepInDays}*(${step}-1) ))
    begtime_d=$(( (${begtimeInDays}-1)%360+1 ))
    begtime_y=$(( (${begtimeInDays}-${begtime_d})/360))

    if [ $(( ${begtimeInDays}+${stepInDays} )) -ge ${endInDays} ]; then 
      endtimeInDays=${endInDays}
      endtime_d=$(( (${endtimeInDays}-1)%360+1 ))
      endtime_y=$(( (${endtimeInDays}-${endtime_d})/360))
    else
      endtimeInDays=$(( ${begtimeInDays}+${stepInDays}-1 ))
      endtime_d=$(( (${endtimeInDays}-1)%360+1 ))
      endtime_y=$(( (${endtimeInDays}-${endtime_d})/360))
    fi

    nextlaunchname="launch_r$(( ${step}+1 ))"
    [ ${iens} -ne 0 ] && nextlaunchname="launch_r${numens}$(( ${step}+1 ))"

    if [ ${NbRun} -lt 10 ]; then
      qstatname=`printf "%.6s_r%d%d\n" ${texp} ${numens} ${step}`
      [ ${iens} -eq 0 ] && qstatname=`printf "%.7s_r%d\n" ${texp} ${step}`
    else
      qstatname=`printf "%.5s_r%d%d\n" ${texp} ${numens} ${step}`
      [ ${iens} -eq 0 ] && qstatname=`printf "%.6s_r%d\n" ${texp} ${step}`
    fi

    cost_step=${lengthInDays}

    echo "${launchname} : ${begtime_y}_${begtime_d}->${endtime_y}_${endtime_d}"
    sizescratch=$(( ${iiens}*3 ))
    echo "#!/bin/bash"                                                                                                    > ${launchname}
    if [ ${slurmflag} -eq 1 ]; then
    echo "###############################################################################" >> ${launchname}
    echo "#                              RUN LOVECLIM                                    " >> ${launchname}
    echo "###############################################################################" >> ${launchname}
    echo "# Define the job name"                                                           >> ${launchname}
    echo "#SBATCH --job-name=${qstatname}"                                                 >> ${launchname}
    echo "#"                                                                               >> ${launchname}
    if [ ${withmail} -eq 1 ]; then
      echo "# Advised: your Email here, for job notification"                              >> ${launchname}
      echo "#SBATCH --mail-user=${mail}"                                                   >> ${launchname}
      echo "#SBATCH --mail-type=ALL"                                                       >> ${launchname}
      echo "#     (ALL = BEGIN, END, FAIL, REQUEUE)"                                       >> ${launchname}
      echo "#"                                                                             >> ${launchname}
    fi
    echo "# Set a pattern for the output file."                                            >> ${launchname}
    echo "#SBATCH --output=${Rundir}/expdir/$texp/log/${texp}_${exp}_${step}.%j"           >> ${launchname}
    echo "#"                                                                               >> ${launchname}
    echo "###############################################################################" >> ${launchname}
    echo "# The requested run-time"                                                        >> ${launchname}
    echo "#"                                                                               >> ${launchname}
    echo "#SBATCH --time=0-${Hour}:${Minute}:${Second}"                                    >> ${launchname}
    echo "#"                                                                               >> ${launchname}
    echo "###############################################################################" >> ${launchname}
    echo "# Requested number of cores. Choose either of, or both of"                       >> ${launchname}
    echo "#"                                                                               >> ${launchname}
    echo "#SBATCH --ntasks=${ncpu}"                                                        >> ${launchname}
    echo "##SBATCH --exclusive"                                                            >> ${launchname}
    echo "##SBATCH --cpus-per-task=1"                                                      >> ${launchname}
    echo "##SBATCH --ntasks-per-node=1"                                                    >> ${launchname}
    echo "#"                                                                               >> ${launchname}
    echo "###############################################################################" >> ${launchname}
    echo "# Requested memory for each core"                                                >> ${launchname}
    echo "#"                                                                               >> ${launchname}
    echo "#SBATCH --mem-per-cpu=${mem}"                                                    >> ${launchname}
    echo "###############################################################################" >> ${launchname}
    echo ""                                                                                >> ${launchname}
    echo "ulimit -s unlimited"                                                             >> ${launchname}
    echo "#export MALLOC_CHECK_=0"                                                         >> ${launchname}
    echo ""                                                                                >> ${launchname}
    echo "###############################################################################" >> ${launchname}

    echo ". ${Rundir}/expdir/$texp/$texp.param"                                                                     >> ${launchname}
    else
    echo "#$ -o ${Rundir}/expdir/$texp/log/${texp}_${exp}_${step}.\$JOB_ID"                                              >> ${launchname}
    echo "# ---------------------------"                                                                                 >> ${launchname}
    echo ". ${Rundir}/expdir/$texp/$texp.param"                                                                          >> ${launchname} 
    fi
    if [[ ${step} -eq 1 ]]; then
    echo "#lock for waiting the loveclim compilation before deploy on each other node"                                   >> ${launchname}
    echo "touch \${Rundir}/expdir/$texp/.lock"                                                                           >> ${launchname}
    fi
    echo " "                                                                                                             >> ${launchname}
    echo "logpath=\${Rundir}/expdir/${texp}/log"                                                                         >> ${launchname}

#boucle sur le temps entre deux step
    echo "ntimer=${begtimeInDays}"                                                                                       >> ${launchname}
    echo "ntimer_d=\$(( (\${ntimer}-1)%360+1 ))"                                                                         >> ${launchname}
    echo "ntimer_y=\$(( (\${ntimer}-\${ntimer_d})/360 ))"                                                                >> ${launchname}
    echo "ntimer_yFormat=\`printf \"%06d\n\" \${ntimer_y}\`"                                                             >> ${launchname}
    echo "ntimer_dFormat=\`printf \"%03d\n\" \${ntimer_d}\`"                                                             >> ${launchname}
    echo "  "                                                                                                            >> ${launchname}
    echo "#Launch Computing"                                                                                             >> ${launchname}
    echo "exp=\"${master_dir}\""                                                                                         >> ${launchname}
    echo "cd \${Rundir}/expdir/$texp/\$exp || exit 1"                                                                    >> ${launchname}
    echo "  "                                                                                                            >> ${launchname}
    echo "${Rundir}/expdir/${texp}/\${exp}/sub.sc \${ntimer} ${optcmp} ${debug_mode} >> \${logpath}/sub\${exp}.log  2>&1">> ${launchname}
    if [ ${step} -ne ${NbRun} ]; then
      echo "cd \${Rundir}/expdir/$texp"                                                                                  >> ${launchname}
      if [ ${slurmflag} -eq 1 ]; then
      echo "sbatch \${Rundir}/expdir/$texp/${nextlaunchname}"         >> ${launchname}
      else
      echo "\${Rundir}/expdir/$texp/${nextlaunchname}"                                                                >> ${launchname}
      fi
    fi
  
  chmod 755 ${launchname}
  done

  [ ${iens} -ne 0 ] && cp -r ${exp} ${master_dir}
  echo "Create sub for ${master_dir}"
  sed "s,{EXP},${master_dir},g" sub.sc > ${master_dir}/sub.sc
  chmod +x ${master_dir}/sub.sc
  sed "s,{EXP},${master_dir},g" postraite.sc > ${master_dir}/postraite.sc
  chmod +x ${master_dir}/postraite.sc
  postname=`printf "post_%.2s%d\n" "${texp}" ${numens}`
  cp launch_rpost launch_rpost${numens}
  sed -i "\
  s,{EXP},${master_dir},g;\
  s,{postname},${postname},g" launch_rpost${numens}
  [ ${iens} -eq 0 ] && mv launch_rpost${numens} launch_rpost
  #update of namelist_ecbilt
  sed -i "s,NUMENS,${numens},g" ${master_dir}/namelist-ecbilt
  [ ${iens} -eq 0 ] && sed -i "s,NUMENS,1,g" ${exp}/namelist-ecbilt

let 'numens += 1'
done
[ ${iens} -ne 0 ] && rm -rf ${exp} launch_rpost
rm sub.sc postraite.sc
master_dir=${exp}
fi
  
 #######################################################################################
 ######### RANGE les Launch et créé un launch Global pour les ensembles ################
 #######################################################################################

if [ ${iens} -ge 2 ]; then 
  cd ${Rundir}/expdir/${texp}
  mkdir -p ${Rundir}/expdir/${texp}/launch
  mv launch_r* launch
  touch Launch_${texp}.sh
  chmod +x Launch_${texp}.sh
  echo "Create Launch_${texp}"
  echo "#!/bin/bash" >> Launch_${texp}.sh
  for i in `seq 1 ${iens}`;
  do
    if [ ${slurmflag} -eq 1 ]; then
    echo "sbatch ${Rundir}/expdir/${texp}/launch/launch_r${i}1" >> Launch_${texp}.sh
    else
    echo "sh launch/launch_r${i}1" >> Launch_${texp}.sh
    fi
  done  
  cd ${Rundir}/expdir/${texp}/launch
  if [ ${slurmflag} -eq 1 ]; then
  sed -i "s/sbatch \${Rundir}\/expdir\/${texp}/sbatch \${Rundir}\/expdir\/${texp}\/launch/g" launch_r*
  else
  sed -i "s/qsub \${Rundir}\/expdir\/${texp}/qsub \${Rundir}\/expdir\/${texp}\/launch/g" launch_r*
  fi
fi
