#!/bin/bash

\rm -f ModelParam.R
bad=0

if [ $# != 3 ] ; then
cat <<eod
Usage : param2R.sh LHCIZE NLHC parameter_file 
eod
exit
fi

LHCSIZE=$1
NLHC=$2
PARAM_FILE=$3

if [ ! -f $PARAM_FILE ] ; then echo fichier $PARAM_FILE inexistant ; exit ; fi
#if [ ! $NLHC -ge 3 ] ; then echo NLHC should be '>=' 3 ; exit ; fi

(( NSCMS = LHCSIZE * NLHC ))
NPARA=`wc -l $PARAM_FILE |awk ' {print $1 }'`

# A automatiser en regardant combien de LES* sont disponibles
# sur chaque cas. 

echo LHCSIZE=$LHCSIZE >> ModelParam.R
echo NLHC=$NLHC >> ModelParam.R
echo NSCMS=$NSCMS >> ModelParam.R
echo NPARA=$NPARA >> ModelParam.R

names=( names lows highs defaults )

for col in  1 2 3 4 ; do
    (( ii = $col -1 ))
    liste='param.'${names[$ii]}='c('
    for val in `awk ' {print $'$col' } ' $PARAM_FILE` ; do
       if [ $col == 1 ] ; then       
         liste=$liste'"'$val'",'
       else
         liste="$liste$val,"
       fi
    done
   echo $liste | sed -e 's/,$/)/' >> ModelParam.R
done


liste="which.logs<-c("
ival=0
ilog=0
for val in `awk ' { print $5 } ' $PARAM_FILE` ; do
   (( ival = $ival + 1 ))
   if [ "$val" = "log" ] ; then
         liste="$liste$ival,"
         ilog=1
   fi
done
if [ $ilog == 0 ]; then 
        echo $liste | sed -e 's/($/()/' >> ModelParam.R
else
        echo $liste | sed -e 's/,$/)/' >> ModelParam.R
fi

cat <<eod>> ModelParam.R
  param.defaults <- param.defaults[1:NPARA]
  param.highs <- param.highs[1:NPARA]
  param.lows <- param.lows[1:NPARA]
  param.names <- param.names[1:NPARA]
eod

cat ModelParam.R

echo '=================================================================='
echo "Generating $NSCMS samples"
echo '=================================================================='
Rscript htune_convertDesign.R

#ls -lrt

# On copie les infos de la wave 1 dans le repertoire WAVE1 (1ere vague de l'history matching)

mkdir WAVE1
# cf plus haut
mv ModelParam.R WAVE1/
# Fichier ASCII simulation id - valeur des parametres
mv Par1D_Wave1.asc WAVE1/
# Fichier R contenant les mêmes informations
mv Wave1.RData WAVE1/

