#!/bin/bash
# Sets up tuning
# If sourced, will only load its functions, otherwise will run the setup
# Modif Najda 8/8/25 : add package seaborn to python environment

set -exvu
unset http_proxy
unset https_proxy

function check_known_issues () {
   if [ -f ~/.Renviron ] ; then
       echo ERROR in $0
       echo A file ~/.Renviron is present on your system
       echo It is a standard file for managing R environments
       echo It is however incompatible with htexplo installation
       echo Remove it after checking it does not interfer with other uses of R
       exit 1
   fi
}


function clean_setup() {
  # A terme mettre le nom des machine dans les noms des renv_* pour pouvoir
  # conserver plusieurs machines / versions en parallele ?
  cd "$installdir"
  rm -rf env.sh  ExeterUQ_MOGP  LES  mogp_emulator  renv_*  venv_*
  cd - > /dev/null
  rm -rf WORK
}

function load_options() {
  # Read cmd line options and give default values

  # Special tricks to deactivate the git clone and so when the network
  # is not available. Can be used only after the setup.sh has been run succesfully
  # once
  network="on" # on/off

  htune_dir=$(pwd)

  # command-line arguments
  model=""
  experience=""
  installdir="../install_shared"
  expdir="WORK"
  python="python"
  clean=0
  # Old (ExeterUQ) or new (ExeterUQ_MOGP) or newer (ExeterUQ_dgpsi) of Exter UQ programs
  _exeter=_MOGP

  while (($# > 0)); do
    case $1 in
      -h|-help|--help) cat <<eof
        $0 [ -model model_name ] [ -exp exp_name ] [-python python_cmd] [ -installdir install_dir ]

        -model      model name (located in ./models) (default <$model>) [available: $(ls models | cat | xargs)]
        -exp        Experience name (default <$experience>)
        -python     Python command to use (default <$python>)
        -installdir Where to install the tuning environment (default <$installdir>)
        -expdir     Where to run the experiments (default <$expdir>)
        -exeter     MOGP|dgpsi (default MOGP)
eof
        exit 0 ;;
      "-model") model=$2; shift; shift;;
      "-exp") experience=$2; shift; shift;;
      "-python") python=$2; shift; shift;;
      "-installdir") installdir=$2; shift; shift;;
      "-expdir") expdir=$2; shift; shift;;
      "-exeter") _exeter=_$2; shift; shift;;
      "clean") clean=1; shift;;
      *) bash $0 -h; exit 1
    esac
  done

  if ! $python -V ; then
    echo "Switching $python->python3"
    python="python3"
  fi

  ExeterUQ="ExeterUQ"$_exeter

  mkdir -p "$installdir"
  mkdir -p "$expdir"
  installdir="$(realpath "$installdir")"
  expdir="$(realpath "$expdir")"

  if [[ ! -d "models/$model" ]]; then
   echo "STOP: $(pwd)/models/$model does not exists"
   $0 -h; exit 1
  fi

  if [[ $experience = "" ]]; then experience="$model"; fi

}

function save_base_environment(){
  echo "set +u" > base_env.profile
  env |grep PATH|sed "s,^,export ,g" >> base_env.profile
}

function load_platform_environment() {
  # platform-specific setup
  local msg

  hostname=$(hostname) ; echo "hostname: $hostname"
  case ${hostname:0:6} in
    "jean-z") cat > env.sh <<eod
      set +u  # <module load> can trigger -u
      module purge
      compilo=19.0.4 # available 2013.0, 2017.2
      module load intel-compilers/\$compilo
      module load intel-mpi/\$compilo
      module load hdf5/1.10.5/intel-\$compilo-mpi
      module load netcdf/4.7.0/intel-\$compilo-mpi
      module load netcdf-fortran/4.4.5/intel-\$compilo-mpi
      module load subversion/1.9.7/gcc-4.8.5
      module load intel-mkl/\$compilo
      module load nco
      module load cdo
      module load ferret
      module load r
      module load python/2.7.16
      login=$(whoami) ; groupe=$(echo \$login | cut -c2-4)
      # Inputation de la consommation sur le groupe \$groupe
      # Peut se changer a la main :
      # groupe=gzi
      submit="sbatch -A \${groupe}@cpu "
      run="srun --label -n "
      SCRATCHD=\$SCRATCH
      STORED=\$STORE
      LMDZD=\$WORK
eod
    ;;

    "spirit"|"ricard"|"ghio")  cat > env.sh <<eod
      set +u  # <module load> can trigger -u
      module purge
      module load R/4.4.1  # also auto-loads python 3.11
      export PATH="/net/nfs/tools/u20/0.22/comp/linux-ubuntu20.04-x86_64/gcc/11.5.0/bin/:\$PATH"  # gcc compatible w/ the R version
      export MPLBACKEND='Agg'  # non-interactive plots
      export TAR=/usr/bin/tar  # for R package install
eod
    ;;

    "pxtrop") if [[ "$hostname" = "pxtropics11" ]] ; then
        msg="export LD_LIBRARY_PATH=\$HOME/.local/lib/:\$LD_LIBRARY_PATH"
      else
        msg="# No special environment needed on this computer"
      fi
      echo "$msg" > env.sh
    ;;
    "beleno") cat > env.sh <<eod
# Using intel compiler for belenos
# Just miss pdfjam
set +u  # <module load> can trigger -u
# module purge tries to unalias condam but the alias does not exist so it raises an error
# so I create a false condam alias so that it can be unaliased...
alias condam="ls"
module ()
{
    eval \`/usr/bin/modulecmd bash \$*\`
}
module purge > /dev/null 2>&1
module load intel > /dev/null 2>&1
module load nco > /dev/null 2>&1
module load eccodes > /dev/null 2>&1
module load cdo > /dev/null 2>&1
module load python/3.7.6 > /dev/null 2>&1
module load R/3.6.1 > /dev/null 2>&1
export PATH="/opt/softs/anaconda3/bin:\$PATH"
export LD_LIBRARY_PATH=/opt/softs/anaconda3/lib/:\$LD_LIBRARY_PATH
export TAR=/usr/bin/tar  # for R package install
eod
    ;;
"oldbel") cat > env.sh <<eod
# env.sh used for belenos with gcc - to keep track  for a while
# I also kept the export path to najda local dir on belenos !!
s config uses software R and pdfjam installed by villefranquen
# relevant paths are added to PATH and LD_LIBRARY_PATH
set +u  # <module load> can trigger -u
# module purge tries to unalias condam but the alias does not exist so it raises an error
# so I create a false condam alias so that it can be unaliased...
alias condam="ls"
module purge
module load gcc/14.1.0
module load openmpi/gnu/4.1.2.1
module load python/3.10.12 
export PATH=/opt/softs/libraries/GCC_5.3.0/cdo-1.7.0/bin/:\$PATH
export LD_LIBRARY_PATH=/opt/softs/gcc/14.1.0/lib64/:/opt/softs/anaconda3/envs/Python310/lib:\$LD_LIBRARY_PATH
export PATH=/home/cnrm_other/ge/mrmc/villefranquen/.local/bin:\$PATH
export LD_LIBRARY_PATH=/home/cnrm_other/ge/mrmc/villefranquen/.local/lib:\$LD_LIBRARY_PATH
export MPLBACKEND='Agg'  # non-interactive plots
export TAR=/usr/bin/tar  # for R package install
eod
    ;;

    *) cat > env.sh <<eod
      # No special environment needed on this computer
eod
  esac


  # write the sed_i command
cat > sed_i<<eod
# define our own sed_i POSIX command to replace sed -i calls
set -e
finam="\${@: -1}"
tmpfi=\$finam.tmpsed
command="\${@:1:\$#-1}"
make_exe=0
test -x \$finam && make_exe=1
sed \$command \$finam > \$tmpfi
mv \$tmpfi \$finam
if [ \$make_exe -eq 1 ] ; then 
  chmod +x \$finam
fi
eod

  # store it in $installdir/bin and add this repo to the PATH
  chmod +x sed_i
  mkdir -p $installdir/bin
  mv sed_i $installdir/bin
  echo "set -u ; export PATH=$installdir/bin:\$PATH ; set +u" >> env.sh

  #chmod +x env.sh
  source ./env.sh
}

function install_python_local {
  version=$1
  # Remove / from the string if running ./setup.sh
  log=$( echo log_${0}.out$$ | sed -e 's:/::g' )
  here=$PWD
  if [[ "$version" == "*"."*"."*" ]] ; then 
    long_version=$version
  else
    case $version in  # get last bugfix of required major.minor version
      3.8*) long_version=3.8.20 ;;
      3.9*) long_version=3.9.23 ;;
      3.10*) long_version=3.10.18 ;;
      *) echo error: will not install python version $version... ; exit 1 ;;
    esac
  fi
  pydir=$installdir/python-$long_version
  mkdir -p $installdir/python-$long_version
  cd $pydir
  echo LALALA >> OUT
  echo  $0 >> OUT
  echo log $log >> OUT
  wget https://www.python.org/ftp/python/$long_version/Python-$long_version.tgz > $log 2>&1
  tar xzf Python-$long_version.tgz
  cd Python-$long_version
  ./configure --prefix=$pydir --enable-shared >> $log 2>&1
  make >> $log 2>&1
  make install >> $log 2>&1
  cd $pydir
  rm Python-$long_version.tgz
  cd $here
  echo $pydir/bin/python3
}

function load_programs() {
  # Testing availability of various programs

  #-----------------------------------------------------------------------
  # Testing availability of various programs
  #-----------------------------------------------------------------------
  if [[ ${hostname:0:6} = "beleno" ]] ; then listprog="R Rscript cdo ncks $python" ; else listprog="R Rscript cdo ncks $python" pdfjam ;fi
  #for exe in R Rscript cdo ncks $python pdfjam ; do
  for exe in $listprog ; do
      if [[ $(which "$exe") = "" ]] ; then echo "STOP: Can't find program <$exe>" ; exit 1 ; fi
  done

  # specific version of python is needed for dgpsi
  if [[ $ExeterUQ == "ExeterUQ_dgpsi" ]] ; then 
    python_version=$($python -V | cut -c8- | cut -d. -f1-2)
    case $python_version in 
      3.9*|3.10*|3.11*|3.12*) echo ok, python version is compatible with dgpsi ;;
      *)
       echo python version is not compatible with dgpsi
       if [ -f $installdir/python*/bin/python3 ] ; then
         echo "found python in $installdir ; switch to $installdir/python*/bin/python3" 
         python=$installdir/python*/bin/python3
       else 
         echo "do you want to install python3.9? (y/n)" 
         read -r ans 
         if [[ "$ans" == "y" || "$ans" == "yes" || "$ans" == "Y" || "$ans" == "Yes" ]] ; then
           python=$(install_python_local 3.9)
         else 
           exit 1 
         fi
       fi
       # set variables to use the correct version of python
       python=$(realpath $python)
       set +u
       export LD_LIBRARY_PATH=$(realpath $installdir/python*/lib/):$LD_LIBRARY_PATH
      ;;
    esac
  fi
}

function load_python_and_R() {
  # Ensures python and R environments are set up correctly
  local python_version
  python_version=$($python -V | cut -c8- | cut -d. -f1-2)
  local venv="venv_$python_version"

  local R_version
  R_version=$(R --version | head -n 1 | cut -c11- | cut -d" " -f1-1)
  local renv="renv_$R_version"

  function load_python() {
    #-----------------------------------------------------------------------
    # Ensure that the same version of mogp or dgpsi tools will be used
    # with this version of the HighTune project
    #-----------------------------------------------------------------------
    
    # MOGP
    #-----------------------------------------------------------------------
    # This commit corresponds to the last one on devel
    # Author: Eric Daub <45598892+edaub@users.noreply.github.com>
    # Date:   Wed Jun 3 18:18:33 2020 +0100
    # mogp_commit=8dd1b6f76b93c8b96540f240b0dc0d6739892d00
    # 19 fevrier 2021 : last commit on master
    #-----------------------------------------------------------------------
    local mogp_commit="0.5.0"
    
    # DGPSI
    #-----------------------------------------------------------------------
    # commit 5a072ea corresponds to dgpsi v2.5.0 on https://github.com/mingdeyu/DGP
    # commit 46ffb81 corresponds to dgpsi v2.6.0 on https://github.com/mingdeyu/DGP
    #-----------------------------------------------------------------------
    local dgpsi_version="2.6.0"

    # Setup virtualenv
    echo $python
    python=$(which "$python")  # can't do before, as we need to have loaded the platform modules
    if [[ ! -d $venv ]]; then
      $python -m venv "$venv"
    fi
    source "$venv/bin/activate"
    echo "Loaded venv, python is $(python -V)"

    if [[ $network = "on" ]]; then
      # Install python mogp
      if [[ $ExeterUQ = "ExeterUQ_MOGP" ]]; then
        # Install additional required packages 
        if [[ ${hostname:0:6} = "beleno" ]] ; then listprog="install patsy matplotlib netcdf4 pandas seaborn" ; else listprog="install patsy matplotlib netcdf4 pandas=2.3.1 seaborn" ;fi
        pip install patsy matplotlib netcdf4 pandas seaborn
        # Try pypi, otherwise git commit
        if ! pip install "mogp-emulator==$mogp_commit"; then
          pip install "git+https://github.com/alan-turing-institute/mogp_emulator@$mogp_commit"
        fi
        ln -sf "$venv/lib/python$python_version/site-packages/mogp_emulator" .  # required by HighTune

      # Install python dgpsi
      elif [[ $ExeterUQ == "ExeterUQ_dgpsi" ]] ; then
        list_req_dgpsi_250="'numpy>=1.18.2'  'numba>=0.51.2'  'matplotlib>=3.2.1'  'tqdm>=4.50.2'  'scipy>=1.4.1'  'scikit-learn>=0.22.0'  'jupyter>=1.0.0'  'dill>=0.3.2  <=0.3.5.1'  'pathos==0.2.9'  'multiprocess==0.70.13'  'psutil>=5.8.0'  'cython>=0.29.30'  'pybind11>=2.10.0'  'pythran>=0.11.0'  'scikit-build>=0.15.0'  'tabulate>=0.8.7'"
        list_req_dgpsi_260='"numpy>=1.18.2"  "numba>=0.51.2"  "matplotlib>=3.2.1"  "tqdm>=4.50.2"  "scipy>=1.4.1"  "scikit-learn>=0.22.0"  "jupyter>=1.0.0"  "dill>=0.3.2"  "pathos>=0.2.9"  "multiprocess>=0.70.13"  "psutil>=5.8.0"  "tabulate>=0.8.7"'
        for req in netcdf4 pandas seaborn
        do  pip install $req  
        done
        pip install 'dgpsi=='$dgpsi_version 
      fi
    fi
  }

  function load_R() {
    # Setup R env variables

    # Install R packages locally
    mkdir -p "$renv"

    if [[ $network = "on" ]]; then
      if [[ $ExeterUQ = "ExeterUQ_MOGP" ]]; then
        test -u $R_version && R_version=$(R --version | head -n 1 | cut -c11- | cut -d" " -f1-1)
        Rlibs_file="$htune_dir/src/Rlibs_${R_version}.txt"
        if [ -f $Rlibs_file ] ; then  # new way
          if ! eval "$htune_dir/src/CheckInstallPackages_.sh" $Rlibs_file ; then
            echo "STOP: Problem encountered when installing R packages, using specifications from file $Rlibs_file"; exit 1
          fi
        else # old way
          # (Amaury) Note: R's package management is terrible. In particular, there is no way to auto-resolve the depencies of a R package for "old" versions of R.
          #                This is particularly a pain when we want to support machines with different versions of R installed.
          #                The list and order of packages below is an attempt to circumvent that, but I hope we can find a cleaner way in the future....
          if ! eval "$htune_dir/src/CheckInstallPackages.sh" Rcpp lattice reticulate Matrix invgamma GenSA far dotCall64 spam fields lhs maps mco ncdf4 shape tensor withr loo MASS pracma mvtnorm flexclust tmvtnorm tictoc ars HI coda MfUSampler ; then
            echo "STOP: Problem encountered when installing R packages"; exit 1
          fi
        fi
      elif [[ $ExeterUQ = "ExeterUQ_dgpsi" ]]; then 
        # le commit 1ce49d6 correspond à la version 2.5.0 sur https://github.com/mingdeyu/dgpsi-R
        # le commit 2ae2e0a correspond à la version 2.6.0+bugfix sur https://github.com/mingdeyu/dgpsi-R
        dgpsiR_commit=2ae2e0a 
        tinydancer_commit=d268375
        if ! eval "$htune_dir/src/CheckInstallPackages.sh" devtools shape mingdeyu/dgpsi-R:$dgpsiR_commit BayesExeter/tinydancer:$tinydancer_commit ; then 
          echo "STOP: Problem encountered when installing R packages for DGPSI version"; exit 1 
        fi
      else
        # (Amaury) Note: not tested
        #
        # When using the original version of ExeterUQ, should install rstan.
        # Touchy ..
        if ! eval "$htune_dir/src/CheckInstallPackages.sh" Rcpp reticulate invgamma GenSA far fields lhs maps mco ncdf4 shape tensor withr loo MASS rstan; then
          echo "STOP: Problem encountered when installing R packages"; exit 1
        fi
      fi
    fi
  }

  load_python
  #echo "set -u ; export R_LIBS=\"$(realpath "$renv"):\$R_LIBS\"; export R_LIBS_USER=\"$(realpath "$renv")\"; source \"$(pwd)/$venv/bin/activate\" ; set +u" >> env.sh
  echo "test -u \$renv && export R_LIBS=\"$(realpath "$renv"):\$R_LIBS\"; export R_LIBS_USER=\"$(realpath "$renv")\"; source \"$(pwd)/$venv/bin/activate\"" >> env.sh
  source env.sh

  load_R
}

function load_exeterUQ() {
  #-----------------------------------------------------------------------
  # Insure the same version of ExeterUQ tools will be used
  # with this version of the HighTune project
  #-----------------------------------------------------------------------
  # This commit corresponds to the last one on master
  # Merge: 089036e e284f7e
  # Author: vicvolodina93 <52710405+vicvolodina93@users.noreply.github.com>
  # Date:   Thu Jun 4 07:59:41 2020 +0100
  # exeter_commit=9e45cde952d75c10515646f412226f6072606b81
  # exeter_commit=ef50736999f1879f19759ca84655a326e7a6b74d
  # 19/02/2021 : exeter_commit=1cdb5c5fedb266e196627336b23ba02cc1375c0a
  # 23/02/2021 : exeter_commit=c67cacb47363389ca767fed5ba30d4a82fb13a2d
  # 25/02/2021 : exeter_commit=7dd118fc0d3da1c3441be2712a6b09a1257e166a
  # 26/02/2021 : exeter_commit=283afc55e10e40e147726827e75cbd3a7dde06e0
  # 01/03/2021
  #-----------------------------------------------------------------------

  exeter_commit=06b008a50b1598d44c9e94a679482ec0896d6cd0
  isnew=0
  if [[ ! -d $ExeterUQ ]] ; then
     git clone "https://github.com/BayesExeter/$ExeterUQ"
     isnew=1
  fi
  cd "$ExeterUQ"
  if [[ $ExeterUQ = ExeterUQ_MOGP ]] ; then 
    set +e
    command -v git > /dev/null 2>&1
    if [ $? -eq 0 ] ; then 
      git checkout $exeter_commit 
    else 
      echo "warning: git command not available, could not checkout commit $exeter_commit in $ExeterUQ"
    fi
    set -e
  fi

  ### Bricolage momentané
  # patch pour que ça marche en 2D (2 paramètres) (Naj)
  if [[ $isnew -eq 1 ]] ; then
    patch HistoryMatching/HistoryMatching.R "$htune_dir/src/patchs/patch_HistoryMatching"
  fi
  cd ..
}

function install_model() {
  echo '======================================================================'
  echo '            3. CONFIGURING THE SPECIFIC EXPERIMENT                    '
  echo '======================================================================'

  if [[ $model = "" ]] ; then  # no model => we setup the very basic example, and run wave 1
    mkdir -p "$expdir/EXEMPLE/"
    if [[ $ExeterUQ == "ExeterUQ_MOGP" ]] ; then exemple=exemple.sh_mogp ; else exemple=exemple.sh_dgpsi ; fi
    cp "$htune_dir/src/$exemple" "$expdir/EXEMPLE/exemple.sh"
    cd "$expdir/EXEMPLE"
    chmod +x exemple.sh
    bash exemple.sh
    echo "CHECK RESULTS IN $expdir/EXEMPLE/"
    exit 0
  fi

  # Copy model-specific files locally
  rm -rf tmp
  mkdir -p tmp/models  # put in tmp/ because setup_$model.sh installs in ../.
  cp -rf "$htune_dir/models/$model" tmp/models
  if [[ $model = "LMDZ" ]]; then
    # set ecrad path for LMDZ
    set -xv
    sed_i -e "s:ecrad_dir=.*.$:ecrad_dir=$(realpath "$htune_dir/models/ECRAD"):" "tmp/models/LMDZ/serie_LMDZ.sh"
    set +xv
  fi

  echo '-----------------------------------------------------------------------'
  echo ' Possibility to have a setup_* specific of a given model'
  echo '-----------------------------------------------------------------------'
  if [[ -f "tmp/models/$model/setup_$model.sh" ]]; then
    cd tmp; "$htune_dir/models/$model/setup_$model.sh"; cd -
  fi
  mkdir -p "$expdir/$experience"
  cp -rf "tmp/models/$model/"* "$expdir/$experience/"
  rm -rf tmp
}

function download_experiment_data() {
  echo '-----------------------------------------------------------------------'
  echo ' Downloading the data relevant to the current experiment'
  echo '-----------------------------------------------------------------------'

  if [[ $model = "ECRAD" ]] ; then

    if [[ ! -d LES1D_ecRad ]] ; then
      echo "Downloading LES/MC results for radiation"
      #wget http://simu:visu2018@www.umr-cnrm.fr/visu-high-tune/data_tuningtool/LES1D_ecRad.tar
      # Naj: temporary change
      wget https://web.lmd.jussieu.fr/~nvillefranque/pub/data/LES1D_ecRad.tar
      tar xvf LES1D_ecRad.tar
      rm -rf LES1D_ecRad.tar
    fi

    if [[ ! -d RAD ]] ; then
      echo "Downloading LES/MC results for radiation"
      #wget http://simu:visu2018@www.umr-cnrm.fr/visu-high-tune/data_tuningtool/RAD.tar
      # Naj: temporary change
      wget https://web.lmd.jussieu.fr/~nvillefranque/pub/data/RAD.tar
      tar xvf RAD.tar
      rm -rf RAD.tar
    fi

  else  # of [[ $model = "ECRAD" ]]

    if [[ ! -d LES ]] ; then
      echo "Downloading LES results from CNRM and LMD"
      #wget http://simu:visu2018@www.umr-cnrm.fr/visu-high-tune/data_tuningtool/les.tar
      wget https://web.lmd.jussieu.fr/~nvillefranque/pub/data/les.tar
      if [[ ! -f les.tar ]] ; then echo "Can not download les.tar" ; exit 1 ; fi
      tar xvf les.tar
      rm -f les.tar
      #-----------------------------------------------------------------------
      # Bricolage avec le cas RCE oceanique. A reprendre
      # cd LES/RCE_OCE/ ; mv REF DAILY ; mkdir -p REF
      # for i in 0 1 ; do
      #   cdo daymean DAILY/LES$i.nc REF/LES$i.nc
      #   ncks -v zf DAILY/LES$i.nc -A REF/LES$i.nc
      #   ncrename -d z,levf REF/LES$i.nc  -O
      #   # On prend le calendrier du cas LMDZ1D en attendant mieux.
      #   # Avec le nouveau format, devrait permettre d'etre propre
      #   # Tous les cas idealises au 1er janvier 2000 ?
      #   ncatted -a "units,time,o,c,days since 1997-11-01 00:00:00" REF/LES$i.nc -O
      # done
      # cd -

      # on supprime le repertoire gabls4 provenant de la base de donnee CNRM-LMD et on le
      # remplace par celui du leslmd.tar (avec le bon calendrier)
      rm -rf LES/GABLS4
      wget --no-check-certificate http://www.lmd.jussieu.fr/~lmdz/HighTune/leslmd.tar
      if [ ! -f leslmd.tar ] ; then echo Can not download leslmd.tar ; exit 1 ; fi
      tar xvf leslmd.tar
      rm -f leslmd.tar

      # Convective files pre processed by Louis d'Alençon en Lamine Thiam
      cd LES
      \rm -rf RCE_OCE AMMA CINDY
      wget http://www.lmd.jussieu.fr/~hourdin/git_d/data/AdditionalLES/les.tar
      tar xvf les.tar
      \rm -f les.tar
      cd -

      #-----------------------------------------------------------------------

    fi  # of [[ ! -d LES ]]
  fi  # of [[ $model = "ECRAD" ]]
}

function create_working_dir() {
  echo '-----------------------------------------------------------------------'
  echo "Creating and installing the working directory $expdir/$experience"
  echo '-----------------------------------------------------------------------'

  local DIR0
  DIR0=$(pwd)

  mkdir -p "$expdir/$experience/log"
  cp -f "$htune_dir/src/"*.py "$htune_dir/src/"*.sh "$htune_dir/src/"*.R "$expdir/$experience/"

  cd "$expdir/$experience"
  if [[ "$model" = "ECRAD" ]] ; then
    ln -sf "$DIR0/RAD" .
    ln -sf "$DIR0/LES1D_ecRad" .
  else
    ln -sf "$DIR0/LES" .
  fi
  # ln -s $DIR0/$ExeterUQ/BuildEmulator .

  ### Bricolage momentané
  # patch while waiting daniel to do the comit
  # on ExetreUQ package
  cp -r "$DIR0/$ExeterUQ/BuildEmulator" .
  mv BuildEmulator_tmp.R BuildEmulator/BuildEmulator.R

  if [[ ! -d HistoryMatching ]]  ; then
    ln -s "$DIR0/$ExeterUQ/HistoryMatching" .
  fi
  if [[ ! -d mogp_emulator ]] ; then
    ln -s "$DIR0/mogp_emulator" .
  fi

  cp "$DIR0/env.sh" .
}

# If sourced: returns, else run setup
if [[ ! "${BASH_SOURCE[0]}" = "$0" ]]; then return 0; fi

check_known_issues
load_options "$@"
if [[ $clean = 1 ]] ; then clean_setup ; exit 0 ; fi
cd "$installdir"
save_base_environment
load_platform_environment
load_programs
load_python_and_R
if [[ $ExeterUQ == "ExeterUQ_MOGP" ]] ; then load_exeterUQ ; fi
install_model
download_experiment_data
create_working_dir

echo "End of $0"
