#!/bin/bash
set +x
#
function usage {
  echo "Usage: $0 [-h] [-l <run_label>] [-s <start_year>] [-a <start_day>] [-n <num_years>] [-i <num_days>] [-r <restart_interval_year>] [-q <restart_interval_days>] [-c <num_step>] [-g <GHG_scenario_label>] [-t <TSI_scenario_label>] [-v <VOLC_scenario_label>] [-e <Veget_scenario_label>] [-z <fwf_scenario_label>] [-k <topo_scenario_label>] [-b <icy_scenario_label>] [-p <imsk_scenario_label>] [-d <loveclim_path>] [-w <workdir_path>] [-o <scratchdir_path>]"
  echo "    -h                         Print this help message"
  echo "    -l <run_label>             A label identifying the experiment   (Default: test)"
  echo "    -s <start_year>            The year in which the run starts     (Default: 1710)"
  echo "    -a <start_day>             The day in which the run starts      (Default: 0)"
  echo "    -n <num_years>             The length of the run in model years (Default: 1)"
  echo "    -i <num_days>              The length of the run in days mod 360 (Default: 0)"
  echo "    -r <restart_interval>      The number of years between writing a restart file (Default: 1)"
  echo "    -q <restart_interval_days> The number of days mod 360 between writing a restart file (Default: 0)"
  echo "    -c <num_step>              Step in the experiment, if 1 build excutable  (Default: 1)"
  echo "    -g <GHG_scenario_label>        A label identifying the scenario    (Default: GHG_B1)"
  echo "    -t <TSI_scenario_label>        A label identifying the scenario    (Default: TSI)"
  echo "    -v <VOLC_scenario_label>       A label identifying the scenario    (Default: Volc)"
  echo "    -e <Veget_scenario_label>      A label identifying the scenario (e pour vEget)   (Default: Veget_PMIP3)"
  echo "    -z <FWF_scenario_label>        A label identifying the scenario"
  echo "    -k <topo_scenario_label>       A label identifying the scenario"
  echo "    -b <icy_scenario_label>        A label identifying the scenario"
  echo "    -p <imsk_scenario_label>       A label identifying the scenario"
  echo "    -d <loveclim_path>         The path where LOVECLIM can be found"  
  echo "    -w <workdir_path>          The path where the workdir can be found"
  echo "    -o <scratchdir_path>       The path where the scratchdir can be found"
  return 0
}
#
printf_format="%06d"
#printf_version="`printf --version`"
#if test "$printf_version" = "--version"; then
#	# Fujitsu VPP printf
#	printf_format="%06s"
#fi
#
# Default values
run_label="test"
start_year=1850
start_day=0
num_years=1
num_days=0
NSKIP=1
NSKIP_days=0
num_step=1
scenario_GHG="GHG_PMIP3"
scenario_TSI="TSI"
scenario_Volc="Volc"
scenario_Veget="Veget_PMIP3"
scenario_FWF="WARNING_no_scenario"
scenario_IMSK="WARNING_no_scenario"
scenario_ICY="WARNING_no_scenario"
scenario_TOPO="WARNING_no_scenario"
#
# Process command-line options
#
# New option from august 2003: num_step
#       if =1 copy, compile source files, build xcutable;
#       if =* do not recompile, use xcutable from step 1
#
getopts "l:s:a:n:i:r:q:c:g:t:v:e:z:k:b:p:d:w:o:h" option
while [ $? = 0 ]; do
  case "$option" in
    l ) EXPERIMENT="$OPTARG" 
        run_label=`echo $EXPERIMENT |  cut -d '/' -f 2`;;
    s )
        if [ `expr $OPTARG : '[1-9][0-9]*'` > 0 ]; then
          start_year="$OPTARG"
        else
          echo "$0: option -s requires an integer argument"
          exit 1
        fi
        ;;
    a ) 
        if [ `expr $OPTARG : '[1-9][0-9]*'` > 0 ]; then
          start_day="$OPTARG"
        else
          echo "$0: option -t requires an integer argument"
          exit 1
        fi
        ;;      
    n )
        if [ `expr $OPTARG : '[1-9][0-9]*'` > 0 ]; then
          num_years="$OPTARG"
        else
          echo "$0: option -n requires a positive integer argument"
          exit 1
        fi
        ;;
    i )
        if [ `expr $OPTARG : '[1-9][0-9]*'` > 0 ]; then
          num_days="$OPTARG"
        else
          echo "$0: option -g requires a positive integer argument"
          exit 1
        fi
        ;;      
    r )
        if [ `expr $OPTARG : '[1-9][0-9]*'` > 0 ]; then
          NSKIP="$OPTARG"
        else
          echo "$0: option -r requires a positive integer argument"
          exit 1
        fi
        ;;
    q )
        if [ `expr $OPTARG : '[1-9][0-9]*'` > 0 ]; then
          NSKIP_days="$OPTARG"
        else
          echo "$0: option -q requires a positive integer argument"
          exit 1
        fi
        ;;
    c ) num_step="$OPTARG"
        ;;
    g ) scenario_GHG="$OPTARG"
        ;;
    t ) scenario_TSI="$OPTARG"
        ;;
    v ) scenario_Volc="$OPTARG"
        ;;
    e ) scenario_Veget="$OPTARG"
        ;;
    z ) scenario_FWF="$OPTARG"
        ;;
    b ) scenario_ICY="$OPTARG"
        ;;
    p ) scenario_IMSK="$OPTARG"
        ;;
    k ) scenario_TOPO="$OPTARG"
        ;;
    d )
        if [ ! ${#OPTARG} -eq 0 ]; then
          emic_dir="$OPTARG"
        else
          echo "$0: option -d is required"
          exit 1
        fi
        ;;
    w )
        if [ ! ${#OPTARG} -eq 0 ]; then
          WORKDIR="$OPTARG"
        else
          echo "$0: option -w is required"
          exit 1
        fi
        ;;
    o )
        if [ ! ${#OPTARG} -eq 0 ]; then
          scratchdir="$OPTARG"
        else
          echo "$0: option -o is required"
          exit 1
        fi
        ;;
    h | ? )
	    usage
	    exit 1
	    ;;
  esac
  OPTARG=""
  getopts "l:s:a:n:i:r:q:c:g:t:v:e:z:k:b:p:d:w:o:h" option
done
rm -rf 0
#
#-------------------------------------------------------------------------------
#
# Component models
ATMOS=ecbilt # Name of atmosphere model: ecbilt
LAND=lbm        # Name of land model: lbm
VEGET=vecode # Name of vegetation model:vecode
OCEAN=clio      # Name of ocean/ice model: clio, fixoc, fom, swamp
OCCYCLE=loch # Name of oc. carb. cycle model:loch
ICESHEET=ism # Name of icesheet model:ism
seaice_in_ocean_model="++seaice_in_ocean_model++"
case ${OCEAN} in
  clio  ) SEAICE="$seaice_in_ocean_model" ;;
  fixoc ) SEAICE="fixtim" ;;
  fom   ) SEAICE="tim" ;;  
  swamp ) SEAICE="tim" ;;
  * )
      echo "$0: Don't know which sea-ice model to use for ${OCEAN}"
      exit 1
      ;;
esac

EMIC="${ATMOS}_${OCEAN}"          # Name of coupled model

NDAYS=$(( $num_years * 360 + ${num_days} ))     # Length of the run in days assuming 360d calendar
NSKIPD=$(( $NSKIP * 360 +${NSKIP_days} ))        # Number of model days between saving restart data

startInDays=$(( ${start_year}*360+${start_day} ))
endInDays=$(( ${startInDays}+${num_years}*360+${num_days} ))
end_day=$(( (${endInDays}-1)%360+1 ))
end_year=$(( (${endInDays}-${end_day})/360 ))
end_day=`printf "%03d" ${end_day}`
end_year=`printf "%06d" ${end_year}`

start_year=`printf $printf_format $start_year`
start_day=`printf "%03d" $start_day`

scratch_dir=${scratchdir}

#work_dir="${emic_dir}/wkdir/${EXPERIMENT}"               # Location of the experiment setup
work_dir="${WORKDIR}/${EXPERIMENT}"                       # Location of the experiment setup
start_dir="${work_dir}/ic${start_year}_${start_day}"      # Location of start of run data
end_dir="${work_dir}/ic${end_year}_${end_day}"            # Location of end of run data
comp_dir="${work_dir}/compil"                             # Location where the model will be compiled
run_dir="${scratch_dir}/${EXPERIMENT}"                    # Location where the model will be run

outputInDays=$(( ${startInDays}+1 ))
output_day=$(( (${outputInDays}-1)%360+1 ))
output_year=$(( (${outputInDays}-${output_day})/360 ))
output_year=`printf ${printf_format} ${output_year}`
output_day=`printf "%03d" ${output_day}`



output_dir="${run_dir}/output${output_year}_${output_day}"  # Location of output data of model

echo "work_dir=" ${work_dir}
echo "start_dir=" ${start_dir}
echo "end_dir=" ${end_dir}
echo "output_dir=" ${output_dir}

MAKE=make

#
#-------------------------------------------------------------------------------
# Support Functions
#-------------------------------------------------------------------------------
#

function check_input_directories {
  echo "Checking for experiment and start data directories ..."
  if [ ! -d $1 ]; then
    echo "Experiment directory $1 does not exist"
    return 1
  fi
  if [ ! -d $2 ]; then
    echo "Startdata directory $2 does not exist"
    return 1
  fi
  return 0
}


  
function setup_run_directory {
  root=$1

  if [ ! -d ${scratch_dir} ]; then
    mkdir -p ${scratch_dir}
  fi
  echo "Creating run directory $root ..."
# 
  if [ -d ${root} ]; then
    rm -fr ${root}
  fi
  
   mkdir -p ${root}/startdata && \
   mkdir -p ${root}/inputdata && \
   mkdir -p ${root}/outputdata/atmos &&\
   mkdir -p ${root}/outputdata/ocean &&\
   mkdir -p ${root}/outputdata/veget &&\
   mkdir -p ${root}/outputdata/ism &&\
   mkdir -p ${root}/outputdata/loch &&\
   chown -R ${USER}:${GROUPS} ${root}
   chmod -R g+rwx ${root}

  if [ ! $? ]; then
    echo "$0: Could not create run directory tree ${root}"
    return 1
  fi
  return $?
}

function setup_comp_directory {
  #
  workdir=$1
  #
  comp_dir="${workdir}/compil"
  #
  echo "Creating compil directories $comp_dir ..."
  if [ -d ${comp_dir} ]; then
   rm -rf ${comp_dir}
  fi
                                                                                                
  mkdir -p ${comp_dir}/sources &&\
  chmod -R g+rwx ${comp_dir}
  if [ ! $? ]; then
    echo "$0: Could not create compil directory tree ${comp_dir}"
    return 1
  fi
  return $?
}
                                                                                                
                                                                                                
function setup_emic {
  # Setup EMIC (coupled model) environent
  #
  model=$1
  rootdir=$2
  rundir=$3
  nyears=$4
  ndays=$5
  runlabely=$6
  runlabeld=$7
  nskip=$8
  nskip_days=$9
  workdir=${10}
  num_step=${11}
   #
  comp_dir="${workdir}/compil"
  #
  echo "Setting up coupled model $model ..."
  # a) Sources
  if [ "$num_step" = "1" ]; then
   cp -p ${rootdir}/${model}/Makefile.run-loveclim ${comp_dir}/Makefile && \
   cp -p ${WORKDIR}/ref/make.macros ${comp_dir} && \
   cp -p ${rootdir}/${model}/sources/*.[fh] ${comp_dir}/sources
  fi
  #
  # b) Input data
  #echo "copy_files ${rootdir}/${model}/inputdata ${rundir}/inputdata"
  #echo "ocbas.dat fractoc.dat labas.dat darea.dat"
  copy_files ${rootdir}/${model}/inputdata ${rundir}/inputdata \
   ocbas.dat \
   fractoc.dat \
   labas.dat \
   darea.dat
  #
  # c) Namelist file
  cat > ${rundir}/namelist <<-EOF
	\$tstepctl
	nyears       = $nyears
	ndays        = $ndays
	irunlabel    = $runlabely
	irunlabeld   = $runlabeld
	iatm         = 6
	ilan         = 1
	iice         = 2
	iobtrop      = 1
	iobclin      = 1
	nwrskip      = $nskip
	nwrskip_days = $nskip_days
	\$end
	EOF
     
   #d)emic.param file
      cp ${workdir}/emic.param ${rundir}/. 
  return $?
}

function setup_FWF {
  # Setup FWF
  
  workdir=$1
  rundir=$2
   
  if [[ "${scenario_FWF}" =~ "NONE" ]]; then
    echo "Disabling FWF"
  else
    echo "Setting up FWF"
    cp ${workdir}/FWF.param ${rundir}/.
    copy_files ${rootdir}/scenario/ ${rundir}/inputdata \
    $scenario_FWF/FWF_WAIS.nc\
    $scenario_FWF/FWF_HUD.nc\
    $scenario_FWF/FWF_LAW.nc

    #copy_files ${start_dir} ${rundir}/inputdata \
    #FWF_WAIS.nc
  fi

  return $?  
}

function setup_atmosphere {
  # Setup atmosphere model environment
  #
  model=$1
  rootdir=$2
  workdir=$3
  rundir=$4
  num_step=$5
  #
  comp_dir="${workdir}/compil"
  #
  echo "Setting up atmosphere model $model ..."
  #
  case ${model} in
    ecbilt )
	     # a) Sources
        if [ "$num_step" = "1" ]; then
	     cp -p ${rootdir}/${model}/sources/*.[fh] ${comp_dir}/sources
        fi
	     #
	     # b) Input data
	     copy_files $files ${rootdir}/${model}/inputdata ${rundir}/inputdata \
	      swrpar/swrref.dat\
	      lwrpar/lwrref.dat\
	      swrpar/swrcoef.dat\
	      lwrpar/lwrcoef.dat\
	      coef.dat\
	      gauss.asc\
	      artiforc/win.dat\
	      artiforc/sum.dat
	     #
	     # c) Namelist file
	     copy_namelist ${model} ${rootdir} ${workdir} ${rundir}/namelist${model}
	     ;;
    * )
	echo "$0: Atmosphere model ${model} is not supported by this script"
	return 1
	;;
  esac
  return $?
}


function setup_land {
  # Setup land model environment
  #
  model=$1
  rootdir=$2
  workdir=$3
  rundir=$4
  num_step=$5
  #
  comp_dir="${workdir}/compil"
  #
  echo "Setting up land model $model ..."
  #
  case ${model} in
    lbm )
 	  # 3.a Sources
        if [ "$num_step" = "1" ]; then
 	  cp -p ${rootdir}/${model}/sources/*.[fh] ${comp_dir}/sources
        fi
 	  #
 	  # 3.b Input data
 	  copy_files ${rootdir}/${model}/inputdata ${rundir}/inputdata \
 	   albedos/albsnow.dat 
 	  #
 	  # 3.c Namelist file
	  copy_namelist ${model} ${rootdir} ${workdir} ${rundir}/namelistland
 	  ;;
    * )
 	echo "$0: Land model ${model} is not supported by this script"
 	return 1
 	;;
  esac
  return $?
}


 
function setup_vegetation {
  # Setup vegetation model environment
  #
  model=$1
  rootdir=$2
  workdir=$3
  rundir=$4
  num_step=$5
  #
  comp_dir="${workdir}/compil"
  #
  echo "Setting up vegetation model $model ..."
  #
  case ${model} in
    vecode )
          # 3.a Sources
          if [ "$num_step" = "1" ]; then
           cp -p ${rootdir}/${model}/sources/*.[fh] ${comp_dir}/sources
          fi
          #
          # 3.b Parameter file
          cp -p ${workdir}/veget.par ${rundir}/. 
           ;;
     * )
        echo "$0: Vegetation model ${model} is not supported by this script"
        return 1
        ;;
  esac
  return $?
}

#

function setup_ocean {
  # Setup ocean model environment
  #
  model=$1
  rootdir=$2
  workdir=$3
  rundir=$4
  num_step=$5
  #
  comp_dir="${workdir}/compil"
  #
  echo "Setting up ocean model $model ..."
  #
  case ${model} in
    clio )
 	   # a) Sources
           if [ "$num_step" = "1" ]; then
 	    cp -p ${rootdir}/${model}/sources/*.{f,h,com} ${comp_dir}/sources
           fi
 	   #
 	   # b) Input data
	   copy_files ${rootdir}/${model}/inputdata ${rundir} \
 	    mozaic.w\
 	    bath.om\
 	    typeaux.dat\
 	    tsobs.om\
 	    pres.int.dat\
 	    pres.int.d.dat\
 	    prcp.int.dat\
 	    prcp.int.d.dat\
 	    cldsa.int.dat\
 	    cldsa.int.d.dat\
 	    ten5.int.dat\
 	    ten5.int.d.dat\
 	    vvent.int.dat\
 	    vvent.int.d.dat\
 	    temp.int.dat\
 	    temp.int.d.dat\
 	    humid.int.dat\
 	    humid.int.d.dat\
 	    runo.int.dat\
 	    runo.int.d.dat\
 	    ust.int.dat\
 	    ust.int.d.dat\
 	    dynami.param\
	    cpointj.dat\
            jmaxl.dat
	    #thermo.param\ (now in ${workdir})
	    #resto.om (Not needed??)
            #masks\ (Not needed??)
            #grids\ (Not needed??)
            #areas\ (Not needed??)
	   
 	   copy_files ${rootdir}/${model}/inputdata ${rundir}/inputdata \
 	    mozaic.w\
 	    albedo.dat
 	   #
 	   # c) Parameter files
	   sed -e s/^CLIO_NDAYS/$NDAYS/ ${workdir}/run.param > ${rundir}/run.param
           cp -f ${rundir}/run.param ${workdir}/run.param
 	   copy_files ${workdir} ${rundir} outp_ocean.param
           copy_files ${workdir} ${rundir} outp_atmos.param
           copy_files ${workdir} ${rundir} outp_veget.param
           optionc=$(awk '/LOCH/ {print $1}' ${workdir}/compil.param)
           if [ "$optionc" = "1" ]; then
             copy_files ${workdir} ${rundir} outp_loch.param
           fi
 	   copy_files ${workdir} ${rundir} thermo.param
 	   ;;
    fixoc )
 	    # a) Sources
            if [ "$num_step" = "1" ]; then
 	     cp -p ${rootdir}/${model}/sources/*.[fh] ${comp_dir}/sources
            fi
 	    #
	    # b) Data files
 	    copy_files ${rootdir}/${model}/inputdata ${rundir}/inputdata \
 	     sst_daily.dat\
 	     albedo.dat
 	    #
 	    # c) Namelist file
 	    # None
 	    ;;
    fom )
 	  # a) Sources
          if [ "$num_step" = "1" ]; then
 	   cp -p ${rootdir}/${model}/sources/*.[fh] ${comp_dir}/sources
          fi  
 	  #
 	  # b) Data files
 	  copy_files ${rootdir}/${model}/inputdata ${rundir}/inputdata \
 	   lakemask.dat \
 	   albedo.dat \
 	   mask.dat \
 	   ocbasins.dat
 	  #
 	  # c) Namelist file
	  copy_namelist ${model} ${rootdir} ${workdir} ${rundir}/namelistocean
 	  ;;
    swamp )
 	    # 4.a Sources
            if [ "$num_step" = "1" ]; then
             cp -p ${rootdir}/${model}/sources/*.[fh] ${comp_dir}/sources
            fi
 	    #
 	    # 4.b Data files
 	    copy_files ${rootdir}/${model}/inputdata ${rundir}/inputdata \
 	     hefx_cli.dat\
 	     sst_cli.dat\
 	     albedo.dat
 	    #
 	    # 4.c Namelist file
	    copy_namelist ${model} ${rootdir} ${workdir} ${rundir}/namelist${model}
 	    ;;
    * )
 	echo "$0: Ocean model ${model} is not supported by this script"
 	return 1
 	;;
  esac
  return $?
}


 function setup_icesheet {
  # Setup icesheet model environment
  #
  model=$1
  rootdir=$2
  workdir=$3
  rundir=$4
  num_step=$5
  #
  comp_dir="${workdir}/compil"
  #
  echo "Setting up icesheet model $model ..."
  #
  case ${model} in
    ism )
          # 3.a Sources
          if [ "$num_step" = "1" ]; then
           cp -p ${rootdir}/${model}/sources/*.{f,com} ${comp_dir}/sources
           cp -p ${rootdir}/${model}/ism.mk ${comp_dir}/.
           cp -p ${rootdir}/${model}/ism.dep ${comp_dir}/.
          fi 
          #
          # 3.b Parameter file
          cp -p ${workdir}/ism.param ${rundir}/.
          cp -p ${workdir}/sens_G.par ${rundir}/.
          cp -p ${workdir}/sens_A.par ${rundir}/.
          # 3.c Input
#         ismInputData=inputdata_11
#         ismInputData=inputdata_12
#         ismInputData=inputdata_13
          ismInputData=inputdata_F
          cp -p ${rootdir}/${model}/${ismInputData}/gism/input/bedrock.10.dat ${rundir}/BED10G
          cp -p ${rootdir}/${model}/${ismInputData}/gism/input/precip.10.dat ${rundir}/PREC10G
          cp -p ${rootdir}/${model}/${ismInputData}/gism/input/coastmask.10.dat ${rundir}/GRMAXG
          cp -p ${rootdir}/${model}/${ismInputData}/gism/input/icethick.10.dat ${rundir}/THI10G
          cp -p ${rootdir}/${model}/${ismInputData}/gism/input/surface.10.dat ${rundir}/SUR10G
          cp -p ${rootdir}/${model}/${ismInputData}/gism/input/icemask.10.dat ${rundir}/GR10G
          cp -p ${rootdir}/${model}/${ismInputData}/gism/input/glacmask.10.dat ${rundir}/GRMAXGG
          cp -p ${rootdir}/${model}/${ismInputData}/gism/input/defmat.10.dat ${rundir}/DEFMATR10
# + ghf
          cp -p ${rootdir}/${model}/${ismInputData}/gism/input/ghf.10.dat ${rundir}/GHF10G
# G forcing
          #cp -p ${rootdir}/${model}/${ismInputData}/gism/input/gripfab_LIG.dat ${rundir}/SEATEMPG
          #cp -p ${rootdir}/${model}/${ismInputData}/gism/input/gripfab_LIG.dat ${rundir}/SEATEMPGtf
# AISM
          cp -p ${rootdir}/${model}/${ismInputData}/aism/input/bed10.dat ${rundir}/BED10A
          cp -p ${rootdir}/${model}/${ismInputData}/aism/input/thi10.dat ${rundir}/THI10A
          cp -p ${rootdir}/${model}/${ismInputData}/aism/input/sur10.dat ${rundir}/SUR10A
          cp -p ${rootdir}/${model}/${ismInputData}/aism/input/mask10.dat ${rundir}/GR10A
          cp -p ${rootdir}/${model}/${ismInputData}/aism/input/defmat10.dat ${rundir}/DEFMATR10
          cp -p ${rootdir}/${model}/${ismInputData}/aism/input/ghf10.dat ${rundir}/GHF10A
# A forcing
          #cp -p ${rootdir}/${model}/${ismInputData}/aism/input/antforcl.dat ${rundir}/SEATEMPA
          #cp -p ${rootdir}/${model}/${ismInputData}/aism/input/antforcl.dat ${rundir}/SEATEMPAtf

# interface
#          cp -p ${rootdir}/${model}/${ismInputData}/surface_elev_Gr3 ${rundir}/.
          cp -p ${rootdir}/${model}/${ismInputData}/lonClio ${rundir}/lonClio
          cp -p ${rootdir}/${model}/${ismInputData}/latClio ${rundir}/latClio
          cp -p ${rootdir}/${model}/${ismInputData}/tms.dat ${rundir}/tms.dat
          # NHISM: copier les fichiers input(INPNH) comme cp -p ${rootdir}/${model}/inputdata/toto  ${rundir}/toto
          cp -p ${rootdir}/${model}/${ismInputData}/toporefism.dat ${rundir}/toporefism.dat
          cp -p ${rootdir}/${model}/${ismInputData}/prec_refism.dat ${rundir}/prec_refism.dat
# hg lwg
          cp -p ${rootdir}/${model}/${ismInputData}/maskLWG.dat ${rundir}/maskLWG.dat
# copied automatically from ic
          #cp -p ${workdir}/temp_ref.dat ${rundir}/temp_ref.dat
          #cp -p ${workdir}/prec_ref.dat ${rundir}/prec_ref.dat
           ;;
     * )
        echo "$0: Icesheet model ${model} is not supported by this script"
        return 1
        ;;
  esac
  return $?
}


function setup_occarb {
  # Setup ocean carbon cycle model environment
  #
  model=$1
  rootdir=$2
  workdir=$3
  rundir=$4
  num_step=$5
  #
  comp_dir="${workdir}/compil"
  #
  echo "Setting up ocean carbon cycle model $model ..."
  #
  case ${model} in
    loch )
          # 3.a Sources
          if [ "$num_step" = "1" ]; then
           cp -p ${rootdir}/${model}/sources/*.f ${comp_dir}/sources/.
           cp -p ${rootdir}/${model}/sources/*.inc ${comp_dir}/sources/.
           cp -p ${rootdir}/${model}/sources/*.com ${comp_dir}/sources/.
           cp -p ${rootdir}/${model}/loch.mk ${comp_dir}/.
           cp -p ${rootdir}/${model}/loch.dep ${comp_dir}/.
          fi
          #
          # 3.b Parameter file
           cp ${rootdir}/${model}/inputdata/*.* ${rundir}/.
           cp -p ${workdir}/runloch.dat ${rundir}/.
           cp -p ${workdir}/OCMIP_Info.dat ${rundir}/.
           cp -p ${workdir}/LOGLOCH.par ${rundir}/.
           cp -p ${workdir}/SEAPIG.par ${rundir}/.

           ;;
     * )
        echo "$0: Ocean carbon cycle model ${model} is not supported by this script"
        return 1
        ;;
  esac
  return $?
}

function setup_seaice {
  # Setup sea-ice model environment
  #
  model=$1
  rootdir=$2
  workdir=$3
  rundir=$4
  num_step=$5
  #
  comp_dir="${workdir}/compil"
  #
  case ${model} in
    $seaice_in_ocean_model )
         echo "Sea-ice model is included with ocean model"
 	 ;;
    tim )
	  echo "Setting up sea-ice model $model ..."
 	  # a) Sources
          if [ "$num_step" = "1" ]; then
           cp -p ${rootdir}/${model}/sources/*.[fh] ${comp_dir}/sources
          fi
 	  #
 	  # b) Data files
 	  # None
 	  #
 	  # c) Namelist file
	  copy_namelist ${model} ${rootdir} ${workdir} ${rundir}/namelistseaice
 	  ;;
    fixtim )
	   echo "Setting up sea-ice model $model ..."
 	   # a) Sources
           if [ "$num_step" = "1" ]; then
            cp ${rootdir}/${model}/sources/*.[fh] ${comp_dir}/sources
           fi
 	   #
 	   # b) Data files
 	   # None
 	   #
	   # c) Namelist file
	   copy_namelist ${model} ${rootdir} ${workdir} ${rundir}/namelistseaice
 	     ;;
    * )
 	echo "$0: Sea-ice model ${model} is not supported by this script"
 	return 1
  esac
  return $?
}


function setup_scenario {
  # Setup scenario data
  #
  ocean_model=$1
  rootdir=$2
  rundir=$3
  numyear=$4
  runlabely=$5
  runlabeld=$6  
  #
  echo "Setting up scenario ..."
  #
  copy_files ${rootdir}/scenario/ ${rundir}/inputdata \
   alb.dat\
   forfr.dat\
   scenario2Xco2.dat\
   mbcs2_cor\
   fresh_for.dat\
   $scenario_GHG/GHG.dat\
   $scenario_GHG/OZONE.dat \
   $scenario_GHG/SUL.nc\
   $scenario_TSI/TSI.dat\
   $scenario_TOPO/berg.nc\
   $scenario_TSI/SAM.dat\
   $scenario_Veget/VEGET.nc

  if [ ! ${scenario_IMSK} = 'NONE' ]; then
    copy_files ${rootdir}/scenario/ ${rundir}/inputdata \
    $scenario_IMSK/icemask.nc
  fi

  if [ ! ${scenario_Volc} = 'NONE' ]; then
   copy_files ${rootdir}/scenario/ ${rundir}/inputdata \
    ${scenario_Volc}/VOLC.dat
   #copy_files ${work_dir} ${rundir}/inputdata \
   # VOLC.dat
  fi

  return $?
}

function setup_startdata {
  # Setup coupled model start data
  #
  startdir=$1
  rundir=$2
  workdir=$3
  rootdir=$4

  #
  echo "Setting up start data ..."
  #
  cp ${startdir}/*.{dat,om,init,rest} ${rundir}/startdata
  cp ${startdir}/*rest* ${rundir}/startdata

  optionc=$(awk '/LOCH/ {print $1}' ${workdir}/compil.param)
  if [ "$optionc" = "1" ]; then
    cp ${startdir}/*.LOLD ${rundir}/startdata
    cp ${startdir}/*.isot ${rundir}/startdata
  fi
  optionc=$(awk '/ISM/ {print $1}' ${workdir}/compil.param)
  if [ "$optionc" = "1" ]; then
    #test -f ${startdir}/*G.gz && cp ${startdir}/*G.gz ${rundir}/startdata && ln -sf ${rundir}/startdata/* ${rundir}
    #test -f ${startdir}/*A.gz && cp ${startdir}/*A.gz ${rundir}/startdata && ln -sf ${rundir}/startdata/* ${rundir}
    #NHISM:copier les startfiles: cp ${startdir}/*N.gz  ${rundir}/startdata
    #[ -f ${rundir}/startdata/*.gz ] && gunzip ${rundir}/startdata/*.gz
    testcp ${startdir}/TforshA ${rundir}/startdata
    cp ${startdir}/*G.gz ${rundir}/startdata
    cp ${startdir}/*A.gz ${rundir}/startdata
    testcp ${startdir}/slTAG ${rundir}/startdata
    gunzip ${rundir}/startdata/*.gz
  fi
  optionc=$(awk '/KATA/ {print $1}' ${workdir}/compil.param)
  if [ ! "$optionc" = "0" ]; then
  #if [ "$optionc" = "2" ]; then
    cp ${rootdir}/clio/inputdata/corr_map_u_x.txt ${rundir}/
    cp ${rootdir}/clio/inputdata/corr_map_u_p.txt ${rundir}/
    cp ${rootdir}/clio/inputdata/corr_map_v_x.txt ${rundir}/
    cp ${rootdir}/clio/inputdata/corr_map_v_p.txt ${rundir}/
    cp ${rootdir}/clio/inputdata/corr_map_taux_p.txt ${rundir}/
    cp ${rootdir}/clio/inputdata/corr_map_taux_x.txt ${rundir}/
    cp ${rootdir}/clio/inputdata/corr_map_tauy_p.txt ${rundir}/
    cp ${rootdir}/clio/inputdata/corr_map_tauy_x.txt ${rundir}/
  fi

  ln -sf ${rundir}/startdata/* ${rundir}

  if [ ! $? ]; then
    echo "$0: Failed to copy start data"
    return 1
  fi
  return 0
}

function setup_preprocess {
  # Preprocessing all code
  #
  rootdir=$1
  workdir=$2
  rundir=$3
  num_step=$4
  #
  comp_dir="${workdir}/compil"
  #
  #
  tmp=`mktemp`
  if [ "$num_step" = "1" ]; then
    #
    echo "Configure source code ..."
    #
    sed -i '/ocean_pert.f/d' ${comp_dir}/Makefile
    sed -i '/ocean_noise.com/d' ${comp_dir}/Makefile
    optionc=$(awk '/ISM/ {print $1}' ${workdir}/compil.param)
    if [ "$optionc" = "1" ]; then
      echo "  --> ISM is ON"
      sed 's/#define ISM 0/#define ISM 1/g' ${comp_dir}/sources/atmphys0.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/atmphys0.f
      sed 's/#define ISM 0/#define ISM 1/g' ${comp_dir}/sources/atmdyn0.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/atmdyn0.f
      sed 's/#define ISM 0/#define ISM 1/g' ${comp_dir}/sources/emic.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/emic.f
      sed 's/#define ISM 0/#define ISM 1/g' ${comp_dir}/sources/landmodel0.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/landmodel0.f
      sed 's/#define ISM 0/#define ISM 1/g' ${comp_dir}/sources/veget.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/veget.f
      sed 's/#define ISM 0/#define ISM 1/g' ${comp_dir}/sources/veget_sub.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/veget_sub.f
      sed 's/#define ISM 0/#define ISM 1/g' ${comp_dir}/sources/veget_wr.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/veget_wr.f
      sed 's/#define ISM 0/#define ISM 1/g' ${comp_dir}/sources/initial0.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/initial0.f
      sed 's/#define ISM 0/#define ISM 1/g' ${comp_dir}/sources/ec_co2oc.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/ec_co2oc.f
      sed 's/#define ISM 0/#define ISM 1/g' ${comp_dir}/sources/inforun.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/inforun.f
      sed 's/#define ISM 0/#define ISM 1/g' ${comp_dir}/sources/thersf.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/thersf.f
      sed 's/#define ISM 0/#define ISM 1/g' ${comp_dir}/sources/comsurf.h > ${tmp}
        mv ${tmp} ${comp_dir}/sources/comsurf.h
      sed 's/#define ISM 0/#define ISM 1/g' ${comp_dir}/sources/comland.h > ${tmp}
        mv ${tmp} ${comp_dir}/sources/comland.h
    else
      sed -i '/ism.mk/d' ${comp_dir}/Makefile
      sed -i '/ism.dep/d' ${comp_dir}/Makefile
      sed -i '/OBJISM/d' ${comp_dir}/Makefile
    fi
    optionc=$(awk '/LOCH/ {print $1}' ${workdir}/compil.param)
    if [ "$optionc" = "1" ]; then
      echo "  --> LOCH is ON"
      sed 's/#define LOCH 0/#define LOCH 1/g' ${comp_dir}/sources/atmphys0.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/atmphys0.f
      sed 's/#define LOCH 0/#define LOCH 1/g' ${comp_dir}/sources/ecbilt0.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/ecbilt0.f
      sed 's/#define LOCH 0/#define LOCH 1/g' ${comp_dir}/sources/emic.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/emic.f
      sed 's/#define LOCH 0/#define LOCH 1/g' ${comp_dir}/sources/veget.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/veget.f
      sed 's/#define LOCH 0/#define LOCH 1/g' ${comp_dir}/sources/veget.h > ${tmp}
        mv ${tmp} ${comp_dir}/sources/veget.h
      sed 's/#define LOCH 0/#define LOCH 1/g' ${comp_dir}/sources/veget_sub.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/veget_sub.f        
    else
      sed -i '/loch.mk/d' ${comp_dir}/Makefile
      sed -i '/loch.dep/d' ${comp_dir}/Makefile
      sed -i '/OBJLOCH/d' ${comp_dir}/Makefile
      sed -i 's/$(IN1LOCH)//g' ${comp_dir}/Makefile
    fi
    optionc=$(awk '/ISOTOPE/ {print $1}' ${workdir}/compil.param)
    if [ "$optionc" = "1" ]; then
      echo "  --> ISOTOPE is ON"
      sed 's/#define ISOTOPE 0/#define ISOTOPE 1/g' ${comp_dir}/sources/clio.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/clio.f
      sed 's/#define ISOTOPE 0/#define ISOTOPE 1/g' ${comp_dir}/sources/ec_co2oc.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/ec_co2oc.f
      sed 's/#define ISOTOPE 0/#define ISOTOPE 1/g' ${comp_dir}/sources/outnet.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/outnet.f
      sed 's/#define ISOTOPE 0/#define ISOTOPE 1/g' ${comp_dir}/sources/scale.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/scale.f
      sed 's/#define ISOTOPE 0/#define ISOTOPE 1/g' ${comp_dir}/sources/thersf.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/thersf.f
      sed 's/#define ISOTOPE 0/#define ISOTOPE 1/g' ${comp_dir}/sources/ice.com > ${tmp}
        mv ${tmp} ${comp_dir}/sources/ice.com
      sed 's/#define ISOTOPE 0/#define ISOTOPE 1/g' ${comp_dir}/sources/para0.com > ${tmp}
        mv ${tmp} ${comp_dir}/sources/para0.com
      sed 's/#define ISOTOPE 0/#define ISOTOPE 1/g' ${comp_dir}/sources/para.com > ${tmp}
        mv ${tmp} ${comp_dir}/sources/para.com
      sed 's/#define ISOTOPE 0/#define ISOTOPE 1/g' ${comp_dir}/sources/comcoup.h > ${tmp}
        mv ${tmp} ${comp_dir}/sources/comcoup.h
      sed 's/#define ISOTOPE 0/#define ISOTOPE 1/g' ${comp_dir}/sources/coupling0.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/coupling0.f
      #
      optionr=$(grep 'Delta O18' ${workdir}/run.param | wc -l)
      if [ "$optionr" = "0" ]; then
        sed -i "16i\#\tDelta O18  : scal0(k,3)\n1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0\n#\tDeuterim   : scal0(k,4)\n2.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0" ${workdir}/run.param
      fi
      sed -i '21d' ${workdir}/run.param
      sed -i "21i\1.\t  0.\t  0.\t 0.  \t122.\t0.\t0.\t0.\t0.     0.     0." ${workdir}/run.param
      sed -i '63d' ${workdir}/run.param
      sed -i "63i\.0\t.0\t-0.1\t-0.3\t-0.3  -0.3  -0.3\t0.1\t0.02 0.02 0.02 0.02" ${workdir}/run.param
      sed -i '71d' ${workdir}/run.param
      sed -i "71i\1.\t1.\t1.\t1.\t0.\t0.  0.  0.  0." ${workdir}/run.param
      sed -i '75d' ${workdir}/run.param
      sed -i "75i\0\t0.\t0.\t0.\t0.\t0.\t0." ${workdir}/run.param
      sed -i '77d' ${workdir}/run.param
      sed -i "77i\-100.   0.      0.\t0.\t0." ${workdir}/run.param
      sed -i '79d' ${workdir}/run.param
      sed -i "79i\290.    34.7    0.\t0.\t0." ${workdir}/run.param
      cp -f ${workdir}/run.param ${rundir}/run.param
    fi
    optionc=$(awk '/CFC/ {print $1}' ${workdir}/compil.param)
    if [ "$optionc" = "1" ]; then
      echo "  --> CFC is ON"
      sed 's/#define CFC 0/#define CFC 1/g' ${comp_dir}/sources/forcng.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/forcng.f
      sed 's/#define CFC 0/#define CFC 1/g' ${comp_dir}/sources/para0.com > ${tmp}
        mv ${tmp} ${comp_dir}/sources/para0.com
      sed 's/#define CFC 0/#define CFC 1/g' ${comp_dir}/sources/outnet.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/outnet.f
      sed 's/#define CFC 0/#define CFC 1/g' ${comp_dir}/sources/trace.com > ${tmp}
        mv ${tmp} ${comp_dir}/sources/trace.com
      sed 's/#define CFC 0/#define CFC 1/g' ${comp_dir}/sources/icdyna.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/icdyna.f
      sed 's/#define CFC 0/#define CFC 1/g' ${comp_dir}/sources/para.com > ${tmp}
        mv ${tmp} ${comp_dir}/sources/para.com
      sed 's/#define CFC 0/#define CFC 1/g' ${comp_dir}/sources/cfc_flx.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/cfc_flx.f
      sed 's/#define CFC 0/#define CFC 1/g' ${comp_dir}/sources/clio.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/clio.f
      sed 's/#define CFC 0/#define CFC 1/g' ${comp_dir}/sources/emic.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/emic.f
      sed -i '15d' ${workdir}/run.param
      sed -i "15i\1.\t  0.\t  0.\t 0.\t0.\t0.\t0.\t0.     0.     0.\t0.\t0." ${workdir}/run.param
      sed -i '57d' ${workdir}/run.param
      sed -i "57i\.0\t.0\t-0.1\t-0.3\t-0.3  -0.3\t-0.3  -0.3  0.1\t0.02 0.02 0.02 0.02 0.02" ${workdir}/run.param
      sed -i '65d' ${workdir}/run.param
      sed -i "65i\1.\t1.\t1.\t1.\t0.\t0.  0.   0.\t0.\t0." ${workdir}/run.param
      sed -i '69d' ${workdir}/run.param
      sed -i "69i\0\t0.\t0.\t0.\t0.\t0.\t0.\t0." ${workdir}/run.param
      sed -i '71d' ${workdir}/run.param
      sed -i "71i\-100.   0.      0.\t0.\t0.\t0." ${workdir}/run.param
      sed -i '73d' ${workdir}/run.param
      sed -i "73i\290.    34.7    0.\t0.\t0.\t0." ${workdir}/run.param
      sed -i "77s/$/ ' '/" ${workdir}/run.param
      sed -i "14i\#\tDelta O18  : scal0(k,3)\n1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0\n#\tDeuterim   : scal0(k,4)\n2.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0\n#\tCFC11      : scal0(k,5)\n0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0\n#\tCFC12      : scal0(k,6)\n0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0" ${workdir}/run.param
      cp -f ${workdir}/run.param ${rundir}/run.param
      cp ${rootdir}/clio/inputdata/cfc1112.atm ${rundir}/cfc1112.atm
      sed -i '140d' ${workdir}/outp_ocean.param
      sed -i "140i\32\t1\t1\t1.\t0." ${workdir}/outp_ocean.param
      sed -i '144d' ${workdir}/outp_ocean.param
      echo -e "33\t1\t1\t1.\t0." >> ${workdir}/outp_ocean.param
      cp -f ${workdir}/outp_ocean.param ${rundir}/outp_ocean.param
    else
      sed -i '/cfc/d' ${comp_dir}/Makefile
    fi
    optionc=$(awk '/TOBI/ {print $1}' ${workdir}/compil.param)
    if [ "$optionc" = "1" ]; then
      echo "  --> TOBI is ON"
      sed 's/#define TOBI 0/#define TOBI 1/g' ${comp_dir}/sources/defcst.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/defcst.f
      sed 's/#define TOBI 0/#define TOBI 1/g' ${comp_dir}/sources/defgrid.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/defgrid.f
      sed 's/#define TOBI 0/#define TOBI 1/g' ${comp_dir}/sources/diftur.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/diftur.f
      sed 's/#define TOBI 0/#define TOBI 1/g' ${comp_dir}/sources/vdiffu.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/vdiffu.f
      sed 's/#define TOBI 0/#define TOBI 1/g' ${comp_dir}/sources/bloc0.com > ${tmp}
        mv ${tmp} ${comp_dir}/sources/bloc0.com
      cp ${rootdir}/clio/inputdata/AVKB_3dim.dat ${rundir}
    fi
    optionc=$(awk '/LGM/ {print $1}' ${workdir}/compil.param)
    if [ "$optionc" = "1" ]; then
      echo "  --> LGM is ON"
      sed 's/#define LGM 0/#define LGM 1/g' ${comp_dir}/sources/atmphys0.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/atmphys0.f
      sed 's/#define LGM 0/#define LGM 1/g' ${comp_dir}/sources/ecbilt0.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/ecbilt0.f
      sed 's/#define LGM 0/#define LGM 1/g' ${comp_dir}/sources/veget.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/veget.f
      sed 's/#define LGM 0/#define LGM 1/g' ${comp_dir}/sources/veget_wr.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/veget_wr.f
      sed 's/#define LGM 0/#define LGM 1/g' ${comp_dir}/sources/landmodel0.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/landmodel0.f
    fi
    optionc=$(awk '/ICY/ {print $1}' ${workdir}/compil.param)
    if [ "$optionc" != "0" ]; then 
      echo "  --> ICY is ON"
      sed 's/#define ICY 0/#define ICY 1/g' ${comp_dir}/sources/atmphys0.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/atmphys0.f
      sed 's/#define ICY 0/#define ICY 1/g' ${comp_dir}/sources/atmdyn0.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/atmdyn0.f
      sed 's/#define ICY 0/#define ICY 1/g' ${comp_dir}/sources/veget.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/veget.f
      sed 's/#define ICY 0/#define ICY 1/g' ${comp_dir}/sources/veget_wr.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/veget_wr.f
    fi
    if [ "$optionc" = "1" ] || [ "$optionc" = "3" ]; then
      sed 's/#define ICY 0/#define ICY 1/g' ${comp_dir}/sources/landmodel0.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/landmodel0.f
    fi
    if [ "$optionc" = "2" ] || [ "$optionc" = "4" ]; then 
      sed 's/#define ICY 0/#define ICY 2/g' ${comp_dir}/sources/landmodel0.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/landmodel0.f
      sed 's/#define ICY 0/#define ICY 2/g' ${comp_dir}/sources/defgrid.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/defgrid.f
    fi 
    optionc=$(awk '/KATA/ {print $1}' ${workdir}/compil.param)
    if [ "$optionc" = "1" ]; then
      echo "  --> KATA is ON"
      sed 's/#define KATA 0/#define KATA 1/g' ${comp_dir}/sources/icdadv.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/icdadv.f
      sed 's/#define KATA 0/#define KATA 1/g' ${comp_dir}/sources/inforun.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/inforun.f
    fi
    if [ "$optionc" = "2" ]; then
      echo "  --> KATA is ON"
      sed 's/#define KATA 0/#define KATA 2/g' ${comp_dir}/sources/ec_co2oc.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/ec_co2oc.f
      sed 's/#define KATA 0/#define KATA 2/g' ${comp_dir}/sources/inforun.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/inforun.f
    fi

    sed -i '/nudging.f/d' ${comp_dir}/Makefile
    sed -i '/st_noise/d' ${comp_dir}/Makefile
    sed -i '/nudging3D.f/d' ${comp_dir}/Makefile

    optionc=$(awk '/ABEL/ {print $1}' ${workdir}/compil.param)
    if [ "$optionc" = "1" ]; then
      echo "  --> ABEL is ON"
      sed 's/#define ABEL 0/#define ABEL 1/g' ${comp_dir}/sources/ec_oc2co.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/ec_oc2co.f
      sed 's/#define ABEL 0/#define ABEL 1/g' ${comp_dir}/sources/atmdyn0.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/atmdyn0.f
    fi
    optionc=$(awk '/FWF/ {print $1}' ${workdir}/compil.param)
    if [ "$optionc" = "1" ]; then
      echo "  --> FWF is ON"
      sed 's/#define FWF 0/#define FWF 1/g' ${comp_dir}/sources/thersf.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/thersf.f
    fi
    optionc=$(awk '/CLOUD/ {print $1}' ${workdir}/compil.param)
    if [ "$optionc" = "1" ]; then
      echo "  --> CLOUD is ON"
      sed 's/#define CLOUD 0/#define CLOUD 1/g' ${comp_dir}/sources/atmphys0.f > ${tmp}
        mv ${tmp} ${comp_dir}/sources/atmphys0.f
    fi
    #
    echo "Preprocessing source code ..."
    # 
    for fichier in $(ls ${comp_dir}/sources/*.f)
    do
      cpp -traditional-cpp -P $fichier > ${tmp}
      mv ${tmp} $fichier
    done
    for fichier in $(ls ${comp_dir}/sources/*.com)
    do
      cpp -traditional-cpp -P $fichier > ${tmp}
      mv ${tmp} $fichier
    done
    for fichier in $(ls ${comp_dir}/sources/*.h)
    do
      cpp -traditional-cpp -P $fichier > ${tmp}
      mv ${tmp} $fichier
    done
  else
    optionc=$(awk '/TOBI/ {print $1}' ${workdir}/compil.param)
    if [ "$optionc" = "1" ]; then
      cp ${rootdir}/clio/inputdata/AVKB_3dim.dat ${rundir} 
    fi
  fi
  #
}


function perform_experiment {
  # Build and run the EMIC executable
  #
  rundir=$1
  workdir=$2
  num_step=$3
  #
  comp_dir="${workdir}/compil"
  #
  echo "Building executable ... ## `date` ##"
  cd ${comp_dir}
  if [ "$num_step" = "1" ]; then
    ${MAKE} clean
    ${MAKE} emic.x
    if [ ! $? ]; then
      echo "$0: Failed to build emic.x"
      return 1
    else
      #add check sum for deployement verification
      md5sum -b emic.x > ${workdir}/compil/sum.txt
    fi
  else
    if [ -f emic.x ]; then
      #add check sum for deployement verification
      md5sum -b emic.x > ${workdir}/compil/sum.txt
    else
      echo "Failed to find emic.x"
      return 1
    fi
  fi
  #if [ -f emic.x ]; then
  #  ${MAKE} clean
  #fi
  #cd ${comp_dir} && ${MAKE} emic.x
  # if succesfull remove objects from comp_dir
  ##########    rm -f sources/*.o
  #
  echo "Running executable ... ## `date` ##"
  
  #
   cd ${rundir}
   rm -f emic.x
   cp ${comp_dir}/emic.x emic.x
   rm -f runhost.txt
   echo `hostname` > runhost.txt
   echo `hostname`
   cp -f runhost.txt ${work_dir}/.
    
   time ./emic.x #>&${rundir}/emic.OU
   if [ ! $? ]; then
     echo "$0: Execution of emic.x failed or was aborted"
     return 1
   fi
   echo "End Running executable ... ## `date` ##"
   return 0
}

function testmv {
  source=$1
  cible=$2
  test -f ${source} && mv ${source} ${cible}
}

function testcp {
  source=$1
  cible=$2
  test -f ${source} && cp ${source} ${cible}
}

function save_results {
  # Save model output and restart data
  #
  rundir=$1
  enddir=$2
  outputdir=${3}/${run_label}
  #
  echo ""
  echo "Organize results ..."
  #
  # All results
  if [ ! -d ${outputdir} ]; then
    mkdir -p ${outputdir}
  fi
  if [ ! -d ${enddir} ]; then
     mkdir -p ${enddir}
  fi
  chmod -R g+rwx ${enddir}

  # Save LOG output
  [ ! -d ${outputdir}/log ] && mkdir -p ${outputdir}/log
  mv ${rundir}/info* ${outputdir}/log/info.${output_year}_${output_day}
  mv ${rundir}/ipcc* ${outputdir}/log/ipcc.${output_year}_${output_day}
  mv ${rundir}/error* ${outputdir}/log/error.${output_year}_${output_day}
  mv ${rundir}/clio3.out ${outputdir}/log/clio3.${output_year}_${output_day}
  mv ${rundir}/mouchard ${outputdir}/log/mouchard.${output_year}_${output_day}
  mv ${rundir}/book* ${outputdir}/log/book.${output_year}_${output_day}
  mv ${rundir}/evolu ${outputdir}/log/evolu.${output_year}_${output_day}

  [ ! -d ${outputdir}/output ] && mkdir -p ${outputdir}/output
  # Save ATMOS output
  [ ! -d ${outputdir}/output/atmos ] && mkdir -p ${outputdir}/output/atmos
  testmv ${rundir}/outputdata/atmos/atmmmyl* ${outputdir}/output/atmos/atmmmyl${output_year}_${output_day}.nc
  testmv ${rundir}/outputdata/atmos/atmmmwp* ${outputdir}/output/atmos/atmmmwp${output_year}_${output_day}.nc
  testmv ${rundir}/outputdata/atmos/atmym* ${outputdir}/output/atmos/atmym${output_year}_${output_day}.nc
  testmv ${rundir}/outputdata/atmos/atmdmwp* ${outputdir}/output/atmos/atmdmwp${output_year}_${output_day}.nc
  testmv ${rundir}/outputdata/atmos/ocheattr* ${outputdir}/output/atmos/ocheattr.${output_year}_${output_day}
  testmv ${rundir}/outputdata/atmos/icesheet ${outputdir}/output/atmos/icesheet.${output_year}_${output_day}
  testmv ${rundir}/outputdata/atmos/ocbasin* ${outputdir}/output/atmos/ocbasin.${output_year}_${output_day}

  # Save OCEAN output
  [ ! -d ${outputdir}/output/ocean ] && mkdir -p ${outputdir}/output/ocean
  testmv ${rundir}/outputdata/ocean/CLIO3_*_mon_avrg.nc ${outputdir}/output/ocean/CLIO3m.${output_year}_${output_day}.nc
  testmv ${rundir}/outputdata/ocean/CLIO3_*_ann_avrg.nc ${outputdir}/output/ocean/CLIO3a.${output_year}_${output_day}.nc
  testmv ${rundir}/outputdata/ocean/CLIO3_*_wday_avrg.nc ${outputdir}/output/ocean/CLIO3d.${output_year}_${output_day}.nc

  # Save LOCH output
  [ ! -d ${outputdir}/output/loch ] && mkdir -p ${outputdir}/output/loch
  testmv ${rundir}/outputdata/loch/LOCH_*_am.nc ${outputdir}/output/loch/LOCHam.${output_year}_${output_day}.nc
  testmv ${rundir}/outputdata/loch/LOCH_*_mm.nc ${outputdir}/output/loch/LOCHmm.${output_year}_${output_day}.nc
  testmv ${rundir}/outputdata/loch/LOCH_*_yearly.nc ${outputdir}/output/loch/LOCH.${output_year}_${output_day}.nc

  # Save EVOVEG output
  [ ! -d ${outputdir}/output/veget ] && mkdir -p ${outputdir}/output/veget
  testmv ${rundir}/outputdata/veget/vegym* ${outputdir}/output/veget/vegym${output_year}_${output_day}.nc
  testmv ${rundir}/evolu ${outputdir}/output/veget/evolu.${output_year}_${output_day}
  testmv ${rundir}/veget.zav ${outputdir}/output/veget/veget.${output_year}_${output_day}.zav
  testmv ${rundir}/veget.outp ${outputdir}/output/veget/veget.${output_year}_${output_day}.outp

  [ ! -d ${outputdir}/output/volc ] && mkdir -p ${outputdir}/output/volc
  testmv ${rundir}/inputdata/VOLC.dat ${outputdir}/output/volc/VOLC.${output_year}_${output_day}.dat

  # Save ISM output
  optionc=$(awk '/ISM/ {print $1}' ${work_dir}/compil.param)
  if [ "$optionc" = "1" ]; then
    [ ! -d ${outputdir}/output/ism ] && mkdir -p ${outputdir}/output/ism
  testmv ${rundir}/SS10G ${outputdir}/output/ism/SS10G_${output_year}_${output_day}
  testmv ${rundir}/CON10G ${outputdir}/output/ism/CON10G_${output_year}_${output_day}
  testmv ${rundir}/SUREVOG ${outputdir}/output/ism/SUREVOG_${output_year}_${output_day}
  testmv ${rundir}/BEDEVOG ${outputdir}/output/ism/BEDEVOG_${output_year}_${output_day}
  testmv ${rundir}/BMAEVOG ${outputdir}/output/ism/BMAEVOG_${output_year}_${output_day}
  testmv ${rundir}/MASG ${outputdir}/output/ism/MASG_${output_year}_${output_day}
  testmv ${rundir}/FWFLUXG ${outputdir}/output/ism/FWFLUXG_${output_year}_${output_day}
  testmv ${rundir}/CONTRTIMEG ${outputdir}/output/ism/CONTRTIMEG_${output_year}_${output_day}
# no PD ice thickness
#  testmv ${rundir}/THI10G ${outputdir}/output/ism/THI10G_${output_year}_${output_day}
  testmv ${rundir}/Tforc ${outputdir}/output/ism/Tforc_${output_year}_${output_day}
  testmv ${rundir}/Pforc ${outputdir}/output/ism/Pforc_${output_year}_${output_day}
# original tforc / CIAI
  testmv ${rundir}/Tlwg ${outputdir}/output/ism/Tlwg_${output_year}_${output_day}
  testmv ${rundir}/Tlr ${outputdir}/output/ism/Tlr_${output_year}_${output_day}
  #testmv ${rundir}/Tforc_in ${outputdir}/output/ism/Tforc_in_${output_year}_${output_day}
  #testmv ${rundir}/Pforc_in ${outputdir}/output/ism/Pforc_in_${output_year}_${output_day}
  testmv ${rundir}/CIAI ${outputdir}/output/ism/CIAI_${output_year}_${output_day}
  testmv ${rundir}/CIAIP ${outputdir}/output/ism/CIAIP_${output_year}_${output_day}
#--
  testmv ${rundir}/ablationG ${outputdir}/output/ism/ablationG_${output_year}_${output_day}
  testmv ${rundir}/CONTRTIMEA ${outputdir}/output/ism/CONTRTIMEA_${output_year}_${output_day}
  testmv ${rundir}/SS10A ${outputdir}/output/ism/SS10A_${output_year}_${output_day}
# case a20
  testmv ${rundir}/SS20A ${outputdir}/output/ism/SS20A_${output_year}_${output_day}
  testmv ${rundir}/SUREVOA ${outputdir}/output/ism/SUREVOA_${output_year}_${output_day}
  testmv ${rundir}/BEDEVOA ${outputdir}/output/ism/BEDEVOA_${output_year}_${output_day}
  testmv ${rundir}/BMAEVOA ${outputdir}/output/ism/BMAEVOA_${output_year}_${output_day}
  testmv ${rundir}/MASA ${outputdir}/output/ism/MASA_${output_year}_${output_day}
  testmv ${rundir}/MASA2 ${outputdir}/output/ism/MASA2_${output_year}_${output_day}
  testmv ${rundir}/AMASA ${outputdir}/output/ism/AMASA_${output_year}_${output_day}
  testmv ${rundir}/AMASA2 ${outputdir}/output/ism/AMASA2_${output_year}_${output_day}
  testmv ${rundir}/CON10A ${outputdir}/output/ism/CON10A_${output_year}_${output_day}
# case a20
  testmv ${rundir}/CON20A ${outputdir}/output/ism/CON20A_${output_year}_${output_day}
  testmv ${rundir}/FWFLUXA ${outputdir}/output/ism/FWFLUXA_${output_year}_${output_day}
# no PD ice thickness
#  testmv ${rundir}/THI10A ${outputdir}/output/ism/THI10A_${output_year}_${output_day}
# case a20
# no PD ice thickness
#  testmv ${rundir}/THI20A ${outputdir}/output/ism/THI20A_${output_year}_${output_day}
  testmv ${rundir}/AbsTempEcb ${outputdir}/output/ism/AbsTempEcb_${output_year}_${output_day}
  testmv ${rundir}/qclim.dat ${outputdir}/output/ism/qclim.dat_${output_year}_${output_day}
  testmv ${rundir}/outputdata/ism/GEOOUTA.nc ${outputdir}/output/ism/GEOOUTA.${output_year}_${output_day}.nc
  testmv ${rundir}/outputdata/ism/GEOOUTG.nc ${outputdir}/output/ism/GEOOUTG.${output_year}_${output_day}.nc
  testmv ${rundir}/outputdata/ism/SMBEVOA.nc ${outputdir}/output/ism/SMBEVOA.${output_year}_${output_day}.nc
  testmv ${rundir}/outputdata/ism/SMBEVOG.nc ${outputdir}/output/ism/SMBEVOG.${output_year}_${output_day}.nc
  testmv ${rundir}/GEOOUT.nc ${outputdir}/output/ism/GEOOUT.${output_year}_${output_day}.nc
  fi

  #NHISM:copier les fichiers output:test -f ${rundir}/AbsPrecEcb  && cp ${rundir}/AbsPrecEcb ${outputdir}/

  #
  # LOCH output
  optionc=$(awk '/LOCH/ {print $1}' ${workdir}/compil.param)
  obinloch=$(awk '/LOCH/ {print $3}' ${workdir}/compil.param)
  if [ "$optionc" = "1" ]; then
    [ ! -d ${outputdir}/output/loch ] && mkdir -p ${outputdir}/output/loch
    if [ "$obinloch" = "1" ]; then
      [ ! -d ${outputdir}/output/loch/LOCHmm ] && mkdir -p ${outputdir}/output/loch/LOCHmm
      [ ! -d ${outputdir}/output/loch/LOCHam ] && mkdir -p ${outputdir}/output/loch/LOCHam
      [ ! -d ${outputdir}/output/loch/LOCH ] && mkdir -p ${outputdir}/output/loch/LOCH
    fi
    # write in LOCH ctl file the experiment name
    sed -e s/LOCH/"${end_year}"/ ${rundir}/llmodim.LOCH | sed -e s/LOLD/"${start_year}"/ > toto
    mv toto ${rundir}/llmodim.LOCH
    # save files
    testcp ${rundir}/llmodim.LOCH ${outputdir}/output/loch/llmodim.${output_year}_${output_day}
    testmv ${rundir}/EVisot.LOCH ${outputdir}/output/loch/EVisot.${output_year}_${output_day}
    testmv ${rundir}/EVloch.LOCH ${outputdir}/output/loch/EVloch.${output_year}_${output_day}
    testcp ${rundir}/tploch.LOCH ${outputdir}/output/loch/tploch.${output_year}_${output_day}
    testcp ${rundir}/FLriver.LOCH ${outputdir}/output/loch/FLriver.${output_year}_${output_day}
    testcp ${rundir}/FLcorre.LOCH ${outputdir}/output/loch/FLcorre.${output_year}_${output_day}
    testcp ${rundir}/ULg_INIT_7515.nc ${outputdir}/output/loch/ULg_INIT.${output_year}_${output_day}.nc
    if [ "$obinloch" = "1" ]; then
      testcp ${rundir}/LLGCM_TT.LOCHmm ${outputdir}/output/loch/LOCHmm/LLGCM_TT.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_SS.LOCHmm ${outputdir}/output/loch/LOCHmm/LLGCM_SS.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_DV.LOCHmm ${outputdir}/output/loch/LOCHmm/LLGCM_DV.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_WW.LOCHmm ${outputdir}/output/loch/LOCHmm/LLGCM_WW.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_UU.LOCHmm ${outputdir}/output/loch/LOCHmm/LLGCM_UU.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_VV.LOCHmm ${outputdir}/output/loch/LOCHmm/LLGCM_VV.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_UH.LOCHmm ${outputdir}/output/loch/LOCHmm/LLGCM_UH.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_US.LOCHmm ${outputdir}/output/loch/LOCHmm/LLGCM_US.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_VH.LOCHmm ${outputdir}/output/loch/LOCHmm/LLGCM_VH.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_VS.LOCHmm ${outputdir}/output/loch/LOCHmm/LLGCM_VS.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_PA.LOCHmm ${outputdir}/output/loch/LOCHmm/LLGCM_PA.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_XX.LOCHmm ${outputdir}/output/loch/LOCHmm/LLGCM_XX.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_WM.LOCHmm ${outputdir}/output/loch/LOCHmm/LLGCM_WM.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_W0.LOCHmm ${outputdir}/output/loch/LOCHmm/LLGCM_W0.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_WF.LOCHmm ${outputdir}/output/loch/LOCHmm/LLGCM_WF.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_EL.LOCHmm ${outputdir}/output/loch/LOCHmm/LLGCM_EL.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_PO.LOCHmm ${outputdir}/output/loch/LOCHmm/LLGCM_PO.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_SE.LOCHmm ${outputdir}/output/loch/LOCHmm/LLGCM_SE.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_DF.LOCHmm ${outputdir}/output/loch/LOCHmm/LLGCM_DF.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_PP.LOCHmm ${outputdir}/output/loch/LOCHmm/LLGCM_PP.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_RR.LOCHmm ${outputdir}/output/loch/LOCHmm/LLGCM_RR.${output_year}_${output_day}    
      testcp ${rundir}/LLGCM_CT.LOCH ${outputdir}/output/loch/LOCH/LLGCM_CT.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_AT.LOCH ${outputdir}/output/loch/LOCH/LLGCM_AT.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_PO.LOCH ${outputdir}/output/loch/LOCH/LLGCM_PO.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_OM.LOCH ${outputdir}/output/loch/LOCH/LLGCM_OM.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_O2.LOCH ${outputdir}/output/loch/LOCH/LLGCM_O2.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_13.LOCH ${outputdir}/output/loch/LOCH/LLGCM_13.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_OR.LOCH ${outputdir}/output/loch/LOCH/LLGCM_OR.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_14.LOCH ${outputdir}/output/loch/LOCH/LLGCM_14.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_SI.LOCH ${outputdir}/output/loch/LOCH/LLGCM_SI.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_AG.LOCH ${outputdir}/output/loch/LOCH/LLGCM_AG.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_M4.LOCH ${outputdir}/output/loch/LOCH/LLGCM_M4.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_S0.LOCH ${outputdir}/output/loch/LOCH/LLGCM_S0.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_FA.LOCH ${outputdir}/output/loch/LOCH/LLGCM_FA.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_BM.LOCH ${outputdir}/output/loch/LOCH/LLGCM_BM.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_BT.LOCH ${outputdir}/output/loch/LOCH/LLGCM_BT.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_PH.LOCH ${outputdir}/output/loch/LOCH/LLGCM_PH.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_BR.LOCH ${outputdir}/output/loch/LOCH/LLGCM_BR.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_PM.LOCH ${outputdir}/output/loch/LOCH/LLGCM_PM.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_P3.LOCH ${outputdir}/output/loch/LOCH/LLGCM_P3.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_P4.LOCH ${outputdir}/output/loch/LOCH/LLGCM_P4.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_FM.LOCH ${outputdir}/output/loch/LOCH/LLGCM_FM.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_FS.LOCH ${outputdir}/output/loch/LOCH/LLGCM_FS.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_MZ.LOCH ${outputdir}/output/loch/LOCH/LLGCM_MZ.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_ZF.LOCH ${outputdir}/output/loch/LOCH/LLGCM_ZF.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_CT.LOCHam ${outputdir}/output/loch/LOCHam/LLGCM_CT.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_AT.LOCHam ${outputdir}/output/loch/LOCHam/LLGCM_AT.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_PO.LOCHam ${outputdir}/output/loch/LOCHam/LLGCM_PO.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_OM.LOCHam ${outputdir}/output/loch/LOCHam/LLGCM_OM.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_O2.LOCHam ${outputdir}/output/loch/LOCHam/LLGCM_O2.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_13.LOCHam ${outputdir}/output/loch/LOCHam/LLGCM_13.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_OR.LOCHam ${outputdir}/output/loch/LOCHam/LLGCM_OR.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_14.LOCHam ${outputdir}/output/loch/LOCHam/LLGCM_14.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_SI.LOCHam ${outputdir}/output/loch/LOCHam/LLGCM_SI.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_AG.LOCHam ${outputdir}/output/loch/LOCHam/LLGCM_AG.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_M4.LOCHam ${outputdir}/output/loch/LOCHam/LLGCM_M4.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_SE.LOCHam ${outputdir}/output/loch/LOCHam/LLGCM_SE.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_PP.LOCHam ${outputdir}/output/loch/LOCHam/LLGCM_PP.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_FA.LOCHam ${outputdir}/output/loch/LOCHam/LLGCM_FA.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_DF.LOCHam ${outputdir}/output/loch/LOCHam/LLGCM_DF.${output_year}_${output_day}
      testcp ${rundir}/LLGCM_RR.LOCHam ${outputdir}/output/loch/LOCHam/LLGCM_RR.${output_year}_${output_day}
    fi
    #tar czf ${outputdir}/output/loch/LOCHam.${output_year}_${output_day}.tar.gz ${rundir}/*.LOCHam
  fi

  # Save RESTART
  [ ! -d ${outputdir}/restart ] && mkdir -p ${outputdir}/restart
  mkdir -p ${rundir}/startdata/res${end_year}_${end_day}
  mv ${rundir}/startdata/*${end_year}_${end_day}* ${rundir}/startdata/res${end_year}_${end_day}/ 2>/dev/null
  testmv ${rundir}/res0.om     ${rundir}/startdata/res${end_year}_${end_day}/rest.om
  testcp ${rundir}/correcw.dat ${rundir}/startdata/res${end_year}_${end_day}/correcw.dat
  testmv ${rundir}/resicb.om   ${rundir}/startdata/res${end_year}_${end_day}/resicb.om
  testcp ${rundir}/resism.om   ${rundir}/startdata/res${end_year}_${end_day}/resism.om
  testmv ${rundir}/EVO10G      ${rundir}/startdata/res${end_year}_${end_day}/EVOING
  testmv ${rundir}/AGEOUTG     ${rundir}/startdata/res${end_year}_${end_day}/AGEING
  testmv ${rundir}/EVO10A      ${rundir}/startdata/res${end_year}_${end_day}/EVOINA
# case a20
  testmv ${rundir}/EVO20A      ${rundir}/startdata/res${end_year}_${end_day}/EVOINA
  testmv ${rundir}/AGEOUTA     ${rundir}/startdata/res${end_year}_${end_day}/AGEINA
  testmv ${rundir}/ACC10REFA   ${rundir}/startdata/res${end_year}_${end_day}/ACC10REFA
  testmv ${rundir}/ACC10A   ${rundir}/startdata/res${end_year}_${end_day}/ACC10A
# case a20
  testmv ${rundir}/ACC20REFA   ${rundir}/startdata/res${end_year}_${end_day}/ACC20REFA
  testmv ${rundir}/ACC20A   ${rundir}/startdata/res${end_year}_${end_day}/ACC20A
  testmv ${rundir}/ArefA       ${rundir}/startdata/res${end_year}_${end_day}/ArefA
  testmv ${rundir}/TforshAout     ${rundir}/startdata/res${end_year}_${end_day}/TforshA
  testmv ${rundir}/FWFCONSTA ${rundir}/startdata/res${end_year}_${end_day}/FWFCONSTA
#hg
  testcp ${rundir}/temp_ref.dat ${rundir}/startdata/res${end_year}_${end_day}/temp_ref.dat
  testcp ${rundir}/prec_ref.dat ${rundir}/startdata/res${end_year}_${end_day}/prec_ref.dat
  testcp ${rundir}/q_ref.dat ${rundir}/startdata/res${end_year}_${end_day}/q_ref.dat
  testcp ${rundir}/sl_ref.dat ${rundir}/startdata/res${end_year}_${end_day}/sl_ref.dat
  testcp ${rundir}/slTAGout     ${rundir}/startdata/res${end_year}_${end_day}/slTAG
#
  testcp ${rundir}/veget.init ${rundir}/startdata/res${end_year}_${end_day}/.
  optionc=$(awk '/LOCH/ {print $1}' ${workdir}/compil.param)
  if [ "$optionc" = "1" ]; then
    testcp ${rundir}/veget.isot ${rundir}/startdata/res${end_year}_${end_day}/.
  fi
  testcp ${rundir}/veget.rest ${rundir}/startdata/res${end_year}_${end_day}/.
  testcp ${rundir}/veget_accu.rest ${rundir}/startdata/res${end_year}_${end_day}/.
  testcp ${rundir}/veget_${end_year}_${end_day}.rest ${rundir}/startdata/res${end_year}_${end_day}/.
  testcp ${rundir}/inputdata/FWF_WAIS.nc ${rundir}/startdata/res${end_year}_${end_day}/FWF_WAIS_pert.nc
  testcp ${rundir}/startdata/res${end_year}_${end_day}/.
  gzip -f ${rundir}/startdata/res${end_year}_${end_day}/*A 2> /dev/null
  gzip -f ${rundir}/startdata/res${end_year}_${end_day}/*G 2> /dev/null

# LOCH restart files if existing
#    # save files
#    # rename for restart
  optionc=$(awk '/LOCH/ {print $1}' ${workdir}/compil.param)
  if [ "$optionc" = "1" ]; then
    cp ${rundir}/*.LOCH ${rundir}/startdata/res${end_year}_${end_day}/.
    rename LOCH LOLD ${rundir}/startdata/res${end_year}_${end_day}/*.LOCH
  fi

# Here everything is moved !!!
  cp ${rundir}/startdata/res${end_year}_${end_day}/* ${enddir}
  mv ${rundir}/startdata/res${end_year}_${end_day} ${outputdir}/restart

    if [ ! $? ]; then
    echo "$0: Failed to save model output and restart data"
    return 1
    fi
 
  return 0
}


function copy_files {
  copy_files_from=$1
  copy_files_to=$2
  shift 2
  files_to_copy=$*
  #
  for file in ${files_to_copy}; do
    cp ${copy_files_from}/$file ${copy_files_to}/
    if [ ! $? ]; then
      echo "$0: Failed to copy ${copy_files_from}/$file to ${copy_files_to}"
      return 1
    fi
    file=`basename ${file}`
    extension=`echo $file | sed 's/.*\.//g'`
    if [ ${extension} == "gz" ]; then
      gzip -d ${copy_files_to}/$file
    fi
  done
  return 0
}


function copy_namelist {
  model=$1
  rootdir=$2
  workdir=$3
  destination=$4
  #
  if [ -f ${workdir}/namelist-${model} ]; then
    namelistfile="${workdir}/namelist-${model}"
  else
    namelistfile="${rootdir}/${model}/default-namelist"
  fi
  cp ${namelistfile} ${destination}
}


#
#-------------------------------------------------------------------------------
#
# Setup environment for each component model. The environment consists of the
# source files, input data files, and namelist or parameter files
#
#-------------------------------------------------------------------------------
#
check_input_directories ${work_dir} ${start_dir} && \
 \
setup_run_directory ${run_dir} && \
if [ "$num_step" = "1" ]; then
 echo "num_step=1"
 setup_comp_directory ${work_dir}
fi && \
setup_emic       ${EMIC}   ${emic_dir} ${run_dir} ${num_years} ${num_days} ${start_year} ${start_day} ${NSKIP} ${NSKIP_days} ${work_dir} ${num_step} && \
setup_FWF  ${work_dir} ${run_dir} && \

setup_atmosphere ${ATMOS}  ${emic_dir} ${work_dir} ${run_dir} ${num_step} && \
setup_land       ${LAND}   ${emic_dir} ${work_dir} ${run_dir} ${num_step} && \
setup_vegetation ${VEGET}  ${emic_dir} ${work_dir} ${run_dir} ${num_step} && \
optionc=$(awk '/ISM/ {print $1}' ${work_dir}/compil.param) && \
if [ "$optionc" = "1" ]; then
  setup_icesheet   ${ICESHEET}  ${emic_dir} ${work_dir} ${run_dir} ${num_step}
fi && \
setup_ocean      ${OCEAN}  ${emic_dir} ${work_dir} ${run_dir} ${num_step} && \
optionc=$(awk '/LOCH/ {print $1}' ${work_dir}/compil.param) && \
if [ "$optionc" = "1" ]; then
  setup_occarb     ${OCCYCLE}  ${emic_dir} ${work_dir} ${run_dir} ${num_step}
fi && \
setup_seaice     "${SEAICE}" ${emic_dir} ${work_dir} ${run_dir} ${num_step} && \
setup_scenario   ${OCEAN}  ${emic_dir} ${run_dir} ${num_years} ${start_year} ${start_day} && \
setup_startdata  ${start_dir} ${run_dir} ${work_dir} ${emic_dir} && \
setup_preprocess ${emic_dir} ${work_dir} ${run_dir} ${num_step} && \
 \
perform_experiment   ${run_dir} ${work_dir} ${num_step} && \
 \
save_results     ${run_dir} ${end_dir} ${output_dir}

exit $?
