#!/bin/bash

if [ `pwd | grep -o HighTune | wc -l` -gt 1 ]
then
  echo "Careful: the HighTune string appears more than once in your current directory:"
  pwd
  echo "This is going to be a problem! Make sure it appears only once!"
  # some sed commands won't work otherwise; this should be improved.
  exit
fi

model=LMDZ
cas=ARMCU/REF
param=param_cldb

if [ $# -eq 1 ] ; then
  model=ECRAD
  cas=ARMCU/008
  param=param
fi

WDIR=BENCH$csv$model
./setup.sh $model $WDIR
cd WORK/$WDIR

./param2R.sh 30 3 $param
if [ $? -eq 0 ]; then
  sed -i "s/WAVEN=.*/WAVEN=1/g" expe_setup.R  # setup experiment
  sed -i "s/targetvar=.*/targetvar=c('theta500', 'qv500', 'zhneb', 'nebmax')/g" expe_setup.R
  sed -i "s/tau=.*/tau=1/g" expe_setup.R
  sed -i "s/Cutoff=.*/Cutoff=3/g" expe_setup.R
# sed -i command is a bit different on mac. We should have the following:
# sed -i "" "s/targetvar=.*/targetvar=c('theta500', 'qv500', 'zhneb', 'nebmax')/g" expe_setup.R
  ./serie_$model.sh $cas 1            # run model with parameters
  if [ $? -eq 0 ]; then
    Rscript htune_ncdf2Rdata.R        # read models outputs and compute metrics
    Rscript htune_EmulatingMultiMetric.R  # emulate and history match

    pdfjam Rplots.pdf 2
    pdf2ps Rplots-2-pdfjam.pdf
    ps2epsi Rplots-2-pdfjam.ps
    epstopdf Rplots-2-pdfjam.epsi
    pdfjam Rplots-2-pdfjam.pdf InputSpace_wave1.pdf --nup 2x1 --landscape --outfile result_wave1.pdf
    evince result_wave1.pdf &

    ./param2Rwave.sh 2 Wave2.RData    # generate new wave parameters
    sed -i "/WAVEN=.*/WAVEN=2/g" expe_setup.R  # setup experiment
    sed -i "/targetvar=.*/targetvar=c('theta500', 'qv500', 'zhneb', 'nebmax')/g" expe_setup.R
    sed -i "/tau=.*/tau=0/g" expe_setup.R
    sed -i "s/Cutoff=.*/Cutoff=3/g" expe_setup.R
    ./serie_$model.sh $cas 2          # run model with parameters
    if [ $? -eq 0 ]; then
    Rscript htune_ncdf2Rdata.R
    Rscript htune_EmulatingMultiMetric.R

    pdfjam Rplots.pdf 2
    pdf2ps Rplots-2-pdfjam.pdf
    ps2epsi Rplots-2-pdfjam.ps
    epstopdf Rplots-2-pdfjam.epsi
    pdfjam Rplots-2-pdfjam.pdf InputSpace_wave2.pdf --nup 2x1 --landscape --outfile result_wave2.pdf
    evince result_wave2.pdf &

    echo '##########################################################'
    echo '    Next version will start heating water at tea time     '
    echo '##########################################################'

    fi
  fi
fi
