#!/bin/bash

#####################################################################
# Transforming the ecrad namelist file that controls ECRAD
# by modifying the value of a subset of parameters randomly
# generated by the htexplo tool
# Author : Maelle Coulon--Decozrens & Najda Villefranque 
#####################################################################

# Some rules for ECRAD parameters name : 
# - ECRAD parameters names must start with RAD (if running with model!=ECRAD)
# - RAD_DZ_OVP must be put before RAD_OVP_HET in the param file
# - 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=
val_dz_ovp=1 #for the evaluation of cloud_inhom scaling from the overlap decorrelation length
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
    # if radiative parameter
    if [[ ${names[$ip]:0:3} == "RAD" ]] ; then
      #echo "Namelist"
      # if we shortened name parameter in param file
      case $name_i in
        RAD_OVH_FAC) name=overhang_factor
          val=$val_i ;;
        RAD_LW_EMISS) name=tune_side_emissivity_factor
          val=$val_i ;;
        RAD_FSD)      name=fractional_std
          val=$val_i ;;
        RAD_DZ_OVP)   name=overlap_decorr_length
          val=$val_i ; val_dz_ovp=$val_i  ;;
	      RAD_OVP_HET) name=cloud_inhom_decorr_scaling 
          val=`echo "${val_i}/${val_dz_ovp}" |bc -l` ;; 
	      RAD_CS|RAD_CS_LOW) name=low_inv_effective_size
          val=`echo "1./${val_i}" |bc -l` ;;
	      RAD_CS_MID) name=middle_inv_effective_size
          val=`echo "1./${val_i}" |bc -l` ;;
	      RAD_CS_HIGH) name=high_inv_effective_size
          val=`echo "1./${val_i}" |bc -l` ;;
	      *) name=${names[$ip]:4} ; val=$val_i ;;
      esac

      keyvals=$keyvals" "$name"="$val
    fi #end if radiative parameter
  fi
  (( ip = $ip + 1 ))
done

if [ "${keyvals}" = "" ] #ECRAD runing offline on SCM profiles with radiative metrics and without radiative parameters
then
  cp ${input} ${output}
else
  ./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
