#!/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...) ########
####################################################################

  #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}
  #autocomplète les chemins de loveclim
  if [ "${loveclimver}" != "AUTO" ]; then
    loveclimver="$loveclimver"
  fi
  if [ "${loveclimdir}" == "AUTO" ]; then
    curentPath=`pwd`
    rootdir=`echo ${curentPath} | sed -e "s/RUN.*//"`
    listeofversion=(`ls -X ${rootdir}/LOVECLIM`)
    if [ "${loveclimver}" == "AUTO" ]; then
      loveclimver=${listeofversion[$(( ${#listeofversion[@]}-1 ))]}
    fi
    loveclimdir=${rootdir}LOVECLIM/${loveclimver}
    if [ ${loveclimver:0:1} == "V" ]; then
      loveclimver=${loveclimver:1:$(( ${#loveclimver}-1 ))}
    fi
  else
    if [ "${loveclimver}" == "AUTO" ]; then
      loveclimver=`echo ${loveclimdir} | sed -e "s/.*LOVECLIM\///; s/\///;"`
    fi
    if [ ${loveclimver:0:1} == "V" ]; then
      loveclimver=${loveclimver:1:$(( ${#loveclimver}-1 ))}
    fi
  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="${Scratchdir}/LOVECLIM$loveclimver"


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


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

  SecondTotal=`python -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))  

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

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

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

cd ${whereisnewexp}/ref/
figlet ${texp}
cd ${whereisnewexp}
echo "################################################################"
echo "LOVECLIM:"
echo -e "\t${loveclimdir}"
echo -e "\tversion = ${loveclimver}"
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 [ ${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
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"
  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
  fi
  echo "OK"
  #if [ $atlas == "1" ]; then
  #  echo -ne "\tAtlas..."
  #  checkfile ${Rundir}/tools/atlas/atlas_ocean.exe
  #  checkfile ${Rundir}/tools/atlas/atlas_oceand.exe
  #  checkfile ${Rundir}/tools/atlas/atlas_atmos.exe
  #  checkfile ${Rundir}/tools/atlas/atlas_atmosd.exe
  #  checkfile ${Rundir}/tools/atlas/atlas_veget.exe
  #  checkfile ${Rundir}/tools/atlas/atlas_vegetd.exe
  #  echo "OK"
  #fi

  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 [ ${kata} -ne 0 ]; then echo -ne "\tKATA..."; echo "ACTIVATED"; 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 [ ${nudging} -eq 1 ]; then echo -ne "\tNUDGING..."; 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" run.param


#############################################
########## CREATE NETCDFOUT.PARAM ###########
#############################################

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


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

  #Pour ISM: le start est le temps de 
  #debut de TOUTE l'experience
  echo "Create ism.param"
  sed -i "s,START,${start_y},g" ism.param


#############################################
############# 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"
  sed -i "\
  s/tobi/${tobi}/g;\
  s/iso/${iso}/g;\
  s/cfc/${cfc}/g;\
  s/fwf/${fwf}/g;\
  s/cloud/${cloud}/g;\
  s/nudging/${nudging}/g;\
  s/lgm/${lgm}/g;\
  s/loch/${loch}/g;\
  s/ensemble/${ensemble}/g;\
  s/ism/${ism}/g;\
  s/abel/${abel}/g;\
  s/kata/${kata}/g" compil.param


#############################################
###########CREATE NUDGING.PARAM ############# 
#############################################

  echo "Create nudging.param"

  CLIOareaPath=${Rundir}/${CLIOarea}
  CLIOareaPath_Format=`echo "${CLIOareaPath}" | sed "s \\/ \\\\\/ g"`
  CLIOgridPath=${Rundir}/${CLIOgrid}
  CLIOgridPath_Format=`echo "${CLIOgridPath}" | sed "s \\/ \\\\\/ g"`

  if [ ${eof_stnoise} != "none" ]; then

    eof_stnoisePath=${Rundir}/${eof_stnoise}
    eof_stnoisePath_Format=`echo "${eof_stnoisePath}" | sed "s \\/ \\\\\/ g"`

  else

    eof_stnoisePath_Format="none"

  fi

  if [ ${res_stnoise} != "none" ]; then

    res_stnoisePath=${Rundir}/${res_stnoise}
    res_stnoisePath_Format=`echo "${res_stnoisePath}" | sed "s \\/ \\\\\/ g"`

  else

    res_stnoisePath_Format="none"

  fi

  if [ ${alpha_stnoise} != "none" ]; then

    alpha_stnoisePath=${Rundir}/${alpha_stnoise}
    alpha_stnoisePath_Format=`echo "${alpha_stnoisePath}" | sed "s \\/ \\\\\/ g"`

  else

    alpha_stnoisePath_Format="none"

  fi

  if [ ${obs_nudg} != "none" ]; then

    obs_nudgPath=${Rundir}/${obs_nudg}
    obs_nudgPath_Format=`echo "${obs_nudgPath}" | sed "s \\/ \\\\\/ g"`

  else

     obs_nudgPath_Format="none"

  fi
 
  stnoise_outpath=${Rundir}/expdir/${texp}/${master_dir}/stnoise_out/${start_yFormat}_${start_dFormat}nois2D.nc
  stnoise_outpath_format=`echo "${stnoise_outpath}" | sed -e "s/\//\\\\\\\\\//g"`
  fcostepf_outpath=${Rundir}/expdir/${texp}/${master_dir}/stnoise_out/${start_yFormat}_${start_dFormat}fcostEPF.txt 
  fcostepf_outpath_format=`echo "${fcostepf_outpath}" | sed -e "s/\//\\\\\\\\\//g"`

  icstart_yFormat2=`printf "%04d\n" ${ic_y}`

  sed -i "\
  s/DIM/${dim_nudg_nois}/g;\
  s/CLIOAREA/${CLIOareaPath_Format}/g;\
  s/CLIOGRID/${CLIOgridPath_Format}/g;\
  s/STNOISEEOF/${eof_stnoisePath_Format}/g;\
  s/STNOISERES/${res_stnoisePath_Format}/g;\
  s/STNOISEALPHA/${alpha_stnoisePath_Format}/g;\
  s/KNOISE/${k_nois}/g;\
  s/SIGMAEPF/${Sigma}/g;\
  s/FCOSTEPF/${fcostepf_outpath_format}/g;\
  s/STNOISEOUT/${stnoise_outpath_format}/g;\
  s/STEPINDAYS/${stepInDays}/g;\
  s/OBSNUDGE/${obs_nudgPath_Format}/g;\
  s/KNUDGE/${k_nudg}/g;\
  s/NUDGEPERIOD/${nudge_period}/g;\
  s/NUDGEMAX/${NudgeMax}/g;\
  s/FILESTARTY/${fileNudgeStartY}/g;\
  s/FILESTARTD/${fileNudgeStartD}/g;\
  s/XPSTARTY/${icstart_yFormat2}/g;\
  s/XPSTARTD/${icstart_dFormat}/g" nudging.param
#   s/NENS/1/g" nudging.param


#############################################
###########CREATE NUDGING3D.PARAM ###########
#############################################

  echo "Create nudging3D.param"

  CLIOareaPath=${Rundir}/${CLIOarea}
  CLIOareaPath_Format=`echo "${CLIOareaPath}" | sed "s \\/ \\\\\/ g"`
  CLIOgridPath=${Rundir}/${CLIOgrid}
  CLIOgridPath_Format=`echo "${CLIOgridPath}" | sed "s \\/ \\\\\/ g"`

  if [ ${eof_stnoise3D} != "none" ]; then

    eof_stnoise3DPath=${Rundir}/${eof_stnoise3D}
    eof_stnoise3DPath_Format=`echo "${eof_stnoise3DPath}" | sed "s \\/ \\\\\/ g"`

  else

    eof_stnoise3DPath_Format="none"

  fi

  if [ ${res_stnoise3D} != "none" ]; then

    res_stnoise3DPath=${Rundir}/${res_stnoise3D}
    res_stnoise3DPath_Format=`echo "${res_stnoise3DPath}" | sed "s \\/ \\\\\/ g"`

  else

    res_stnoise3DPath_Format="none"

  fi

  if [ ${alpha_stnoise3D} != "none" ]; then

    alpha_stnoise3DPath=${Rundir}/${alpha_stnoise3D}
    alpha_stnoise3DPath_Format=`echo "${alpha_stnoise3DPath}" | sed "s \\/ \\\\\/ g"`

  else

    alpha_stnoise3DPath_Format="none"

  fi

  if [ ${obs_nudg3D} != "none" ]; then

    obs_nudg3DPath=${Rundir}/${obs_nudg3D}
    obs_nudg3DPath_Format=`echo "${obs_nudg3DPath}" | sed "s \\/ \\\\\/ g"`

  else

     obs_nudg3DPath_Format="none"

  fi
 
  stnoise_outpath=${Rundir}/expdir/${texp}/${master_dir}/stnoise_out/${start_yFormat}_${start_dFormat}nois3D.nc
  stnoise_outpath_format=`echo "${stnoise_outpath}" | sed -e "s/\//\\\\\\\\\//g"`
 
  sed -i "\
  s/DIM/${dim_nudg_nois}/g;\
  s/CLIOAREA/${CLIOareaPath_Format}/g;\
  s/CLIOGRID/${CLIOgridPath_Format}/g;\
  s/STNOISEEOF/${eof_stnoise3DPath_Format}/g;\
  s/STNOISERES/${res_stnoise3DPath_Format}/g;\
  s/STNOISEALPHA/${alpha_stnoise3DPath_Format}/g;\
  s/STNOISEOUT/${stnoise_outpath_format}/g;\
  s/STEPINDAYS/${stepInDays}/g;\
  s/OBSNUDGE/${obs_nudg3DPath_Format}/g;\
  s/NUDGEPERIOD/${nudge_period}/g;\
  s/NUDGEMAXTEMP/${NudgeMax_temp}/g;\
  s/NUDGEMAXSALT/${NudgeMax_salt}/g;\
  s/FILESTARTY/${fileNudgeStartY}/g;\
  s/FILESTARTD/${fileNudgeStartD}/g;\
  s/XPSTARTY/${icstart_yFormat2}/g;\
  s/XPSTARTD/${icstart_dFormat}/g;\
  s/NENS/1/g"  nudging3D.param

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

  echo "Create namelist-ecbilt.param"
  iiens=${iens}
  [ ${iens} -ne 0 ] && iiens=1
  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/CLOUD/${cloud}/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" veget.par


#############################################
############ CREATE RUNLOCH.DAT #############
#############################################

  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/lriver/${lriver}/g" runloch.dat


#############################################
############ CREATE TPLOCH.LOLD #############
#############################################

  echo "Create tploch.LOLD"
  sed -i "s,YEAR1_loch,${YEAR1_loch},g" tploch.LOLD
  # horloge de Loch pour run equilibre


#############################################
############# 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


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

  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/${ddfsi}/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

  
#############################################
############### 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}; cp $exp/tploch.LOLD $exp/${icstart_yFormat}_${icstart_dFormat}"
  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
  
  
#############################################
########## COPY MASTER PARAM FILE ###########
#############################################

  echo "Copy $masterparam";
  cp -f $masterparam ${Rundir}/expdir/$texp/$texp.param
  sed -i "\
  s/loveclimdir=AUTO/loveclimdir=${loveclimdirFormat}/g;\
  s/{LOVECLIMVER}/${loveclimver}/g;\
  s/loveclimver=AUTO/loveclimver=${loveclimver}/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,{LOVECLIMVER},${loveclimver},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,{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}
  echo "#$ -o ${Rundir}/expdir/$texp/log/{postname}.\$JOB_ID"      >> ${launchname}
  echo "# ---------------------------"                             >> ${launchname}
  timefin=$(( ${start_y}+${length_y} ))
  echo "path_post=${Rundir}/expdir/${texp}"                        >> ${launchname}
  echo "iatmos=1"                                                  >> ${launchname}
  echo "iocean=1 ; ioceanevo=1"                                    >> ${launchname}
  echo "iveget=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

    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}
    echo "#$ -o ${Rundir}/expdir/$texp/log/${texp}_${exp}_${step}.\$JOB_ID"                                              >> ${launchname}
    echo "# ---------------------------"                                                                                 >> ${launchname}
    echo ". ${Rundir}/expdir/$texp/$texp.param"                                                                          >> ${launchname} 
    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}
      echo "\${Rundir}/expdir/$texp/${nextlaunchname}"                                                                >> ${launchname}
    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
  #update of nudging.param
  sed -i "s,NENS,${numens},g" ${master_dir}/nudging.param                                            
  [ ${iens} -eq 0 ] && sed -i "s,NENS,1,g" ${exp}/nudging.param

let 'numens += 1'
done
[ ${iens} -ne 0 ] && rm -rf ${exp} launch_rpost
rm sub.sc postraite.sc
master_dir=${exp}
fi

  
#############################################
######### CREATE ATLAS FILES ################
#############################################
#if [ $atlas == "1" ]; then
#
#  cd ${Rundir}/tools/atlas
#
#  cp atlas_ocean.exe ${Rundir}/expdir/$texp/$exp
#  cp atlas_atmos.exe ${Rundir}/expdir/$texp/$exp
#  cp atlas_veget.exe ${Rundir}/expdir/$texp/$exp
#  #cp atlas_ism.exe ${Rundir}/expdir/$texp/$exp
#
#  echo "Create atlas files"
#  cd ${Rundir}/expdir/$texp/$exp
#  chmod 755 atlas*
#
#  nyr=$(( ${end_y}-${start_y} ))
#  atlas_path="${Rundir}/tools"
#
#  sed -i "\
#  s,EXPNAME,${texp},g;\
#  s,START,${start_y},g;\
#  s,END,${end_y},g;\
#  s,NYR,${nyr},g;\
#  s,ATLAS_Rundir,${Rundir},g;\
#  s,ATLAS_SRC,${atlas_path},g" atlas_ocean.exe
#  sed -i "\
#  s,EXPNAME,${texp},g;\
#  s,START,${start_y},g;\
#  s,END,${end_y},g;\
#  s,NYR,${nyr},g;\
#  s,ATLAS_Rundir,${Rundir},g;\
#  s,ATLAS_SRC,${atlas_path},g" atlas_atmos.exe
#  sed -i "\
#  s,EXPNAME,${texp},g;\
#  s,START,${start_y},g;\
#  s,END,${end_y},g;\
#  s,NYR,${nyr},g;\
#  s,ATLAS_Rundir,${Rundir},g;\
#  s,ATLAS_SRC,${atlas_path},g" atlas_veget.exe
#  #sed -i "\
#  #s,EXPNAME,${texp},g;\
#  #s,START,${start_y},g;\
#  #s,END,${end_y},g;\
#  #s,NYR,${nyr},g;\
#  #s,ATLAS_Rundir,${Rundir},g;\
#  #s,ATLAS_SRC,${atlas_path},g" atlas_ism.exe
#
#  cd ..
#
#  echo "Create sub.atlas"
#  launchname="sub.atlas"
#  echo "#!/bin/bash"                                                > ${launchname}
#  echo "# memory request"                                          >> ${launchname}
#  echo "#$ -S /bin/bash"                                           >> ${launchname}
#  echo "#$ -N atlas_${texp}"                                       >> ${launchname}
#  echo "#$ -l mf=${mem}"                                           >> ${launchname}
#  echo "#$ -l h_rt=${Hour}:${Minute}:${Second}"                    >> ${launchname}
#  echo "#$ -l nb=false"                                            >> ${launchname}
#  echo "##$ -l hm=FALSE"                                           >> ${launchname}
#  echo "#$ -pe ${queue} $(( ${ncpu} ))"                            >> ${launchname}
#  echo "#$ -R y"                                                   >> ${launchname}
#  echo "#$ -V"                                                     >> ${launchname}
#  echo "#$ -cwd"                                                   >> ${launchname}
#  echo "#$ -j y"                                                   >> ${launchname}
#  echo "#$ -o ${Rundir}/expdir/$texp/log/atlas_${texp}.\$JOB_ID"   >> ${launchname}
#  if [ ${withmail} -eq 1 ]; then
#    echo "#$ -m be"                                                >> ${launchname}
#    echo "#$ -M ${mail}"                                           >> ${launchname}
#  fi
#  echo "# ---------------------------"                             >> ${launchname}
#  echo ". /etc/profile.d/modules.sh"                          >> ${launchname}
#  echo "module purge"                                              >> ${launchname}
#  echo "module add shared intel/cce intel/fce openmpi/intel"       >> ${launchname}
#  echo "module add sge/6.1"                                        >> ${launchname}
#  echo ""                                                          >> ${launchname}
#  echo "uname -n"                                                  >> ${launchname}
#  echo "cd ${Rundir}/expdir/$texp/$exp"                            >> ${launchname}
#  echo "./atlas_atmos.exe"                                         >> ${launchname}
#  echo "./atlas_ocean.exe"                                         >> ${launchname}
#  echo "./atlas_veget.exe"                                         >> ${launchname}
#  #echo "./atlas_ism.exe"                                           >> ${launchname}
#
#  if [ $atlasd == "1" ]; then
#
#    cd ${Rundir}/tools/atlas
#
#    cp atlas_oceand.exe ${Rundir}/expdir/$texp/$exp
#    cp atlas_atmosd.exe ${Rundir}/expdir/$texp/$exp
#    cp atlas_vegetd.exe ${Rundir}/expdir/$texp/$exp
#
#    cd ${Rundir}/expdir/$texp/$exp
#    chmod 755 atlas*
#
#    sed -i "\
#    s,EXPNAME,${texp},g;\
#    s,START,${start_y},g;\
#    s,END,${end_y},g;\
#    s,NYR,${nyr},g;\
#    s,ATLAS_SRC,${atlas_path},g" atlas_oceand.exe
#    sed -i "\
#    s,EXPNAME,${texp},g;\
#    s,START,${start_y},g;\
#    s,END,${end_y},g;\
#    s,NYR,${nyr},g;\
#    s,ATLAS_SRC,${atlas_path},g" atlas_atmosd.exe
#    sed -i "\
#    s,EXPNAME,${texp},g;\
#    s,START,${start_y},g;\
#    s,END,${end_y},g;\
#    s,NYR,${nyr},g;\
#    s,ATLAS_SRC,${atlas_path},g" atlas_vegetd.exe
#
#    cd ..
#
#    echo "./atlas_atmosd.exe"                                        >> ${launchname}
#    echo "./atlas_oceand.exe"                                        >> ${launchname}
#    echo "./atlas_vegetd.exe"                                        >> ${launchname}
#
#  fi
#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
    echo "sh launch/launch_r${i}1" >> Launch_${texp}.sh
  done  
  cd ${Rundir}/expdir/${texp}/launch
  sed -i "s/qsub \${Rundir}\/expdir\/${texp}/qsub \${Rundir}\/expdir\/${texp}\/launch/g" launch_r*
fi
