#!/bin/bash

#####################################################################
# Transforming the MesoNH namelist file that controls MESONH
# by modifying the value of a subset of parameters randomly
# generated by the htexplo tool
# Author : Najda Villefranque inspired by runECRAD/nam2nam.sh
#####################################################################

# Some rules for MESONH parameters name : 
# - MESONH parameters names must start with PRE or EXS
# - parameter names to scale input profil must contains *scale* in it

while (($# > 0)) ; do
  #echo OPTION $1 $2
  case $1 in
    -names) names=( `echo $2 | sed -e 's/,/ /g'` ) ; shift ; shift ;;
    -vals) vals=( `echo $2 | sed -e 's/,/ /g'` ) ; shift ; shift ;;
    -input) input=$2 ; shift ; shift ;;
    -output) output=$2 ; shift ; shift ;;
    -help|-h) echo Usage "$0 -names names -vals vals -input input -output output" ; exit ;;
    *) $0 -help ; exit
  esac
done

ip=1
keyvals=
sclvals=
while [ $ip -lt ${#vals[*]} ] ; do
  name_i=${names[$ip]}
  val_i=${vals[$ip]}
  if [[ ${names[$ip]} == *"scale"* ]] ; then
    sclvals=$sclvals" "$name_i"="$val_i
  else
    name=${name_i}
    val=$val_i
    keyvals=$keyvals" "$name"="$val
  fi
  (( ip = $ip + 1 ))
done

if [ "${keyvals}" = "" ] 
then
  #ECRAD runing offline on SCM profiles with radiative metrics and without radiative parameters
  cp ${input} ${output}
else
  ./mnh_change_namelist.sh ${input} ${output} ${keyvals}
fi

if [ "$sclvals" != "" ] ; then
  path=`echo $output | awk  -F/ ' { for (i=2;i<NF;i++) res=res"/"$i} END {print res} '`
  echo $sclvals >> $path/sclvals.txt
fi
