#!/bin/bash

#. env.sh
#set -vx

##############################################################################
# Computing metrics from LES and SCM
# Result in csv format
# Auteur: F Couvreux, R Honnert, F Hourdin, N Villefranque, C Rio, n'co
##############################################################################
#
# metrics are specified in list_case
# metrics names follow the syntax
#
# CASE_SUBCASE_METRICS_T1_T2
# T1 and T2 are initial and final time step for time averages
# 
# unless it is a radiative metric, in which case the syntax is
# RAD_CASE_SUBCASETIME_METRICS_SZA1_SZA2
#
# available METRICS :
# ===================
#
# 1/ zav-400-600-var  -> variable "var" averaged between 400 and 600 m
#
# 2/ Ay-var -> integral ( min ( var -var(t=1) ) dz ) / integral ( dz )
#           integral taken from 0 to  zmax
#
# 3/ nebzave, neb2zave, neb4zave : Effective cloud height 
#           = int ( neb^p z dz ) / int ( neb^p dz ) with  p=1, 2 or 4
#
# 4/ nebmax : maximum cloud fraction on the column
#
# 5/ nebzmin, nebzmax : minimum/maximum cloud height
#
# 6/ lwp : liquid water path
#
# TBD :
# =====
# 1/ integrals are computed assuming rho=1 because rho is not systematically avalble
# 2/ the time average is coded for zav metrics only
#
##############################################################################

wave=1
sepm="_"

#----------------------------------------------------------------
# Reading arguments
#----------------------------------------------------------------

list_case=""
while (($# > 0)) ; do
  case $1 in
    -wave) wave=$2 ; echo WAVE $wave ;  shift ; shift ; echo OPTION $* ;;
    -help|-h) echo Usage "$0 [-wave N] [metrics1] [metrics2] ..." ; exit ;;
    *) list_case=( ${list_case[*]} $1 ) ; shift ;;
  esac
done

# Default metrics
if [[ ${list_case[*]} = "" ]] ; then list_case=( ARMCU_REF_zav-400-600-theta_9_9 ) ; fi
	
# if RAD and LES repos are not defined (e.g. in .env) :
if [[ "$RAD" = "" ]] ; then RAD=RAD ; fi
if [[ "$LES" = "" ]] ; then LES=LES ; fi

wavedir=WAVE$wave
mkdir -p "$wavedir/individual_metrics"

# where final metrics values will be stored
metrics_file_ref=${wavedir}/metrics_REF_$wave.csv

# Remove old files
rm -f "metrics_$wave.csv" "metrics_LES_$wave.csv "

#-------------------- util functions -------------------------- #
is_metric_rad() {
 if [[ ${metric_name:0:3} == "RAD" ]] ; then echo 1 ; else echo 0 ; fi
}

is_metric_ica() {
 if [[ ${metric_name:3:3} == "ICA" ]] ; then echo 1 ; else echo 0 ; fi
}

add_to_metric_file() {
  # create if does not exist, concatenate (column-wise) otherwise
  indiv_metric=$1
  store_metric=$2
  if [[ ! -f $store_metric ]]
  then
    cp -f "$indiv_metric" "$store_metric"
  else
    cut -d, -f2 "$indiv_metric" |paste -d, "$store_metric" - > temp
    mv temp "$store_metric"
  fi
  mv "$indiv_metric" "$wavedir/individual_metrics"
}
#-------------------------------------------------------------- #

echo "-----------------------------------------------------------"
echo "STARTING loop on metrics"
echo "-----------------------------------------------------------"

function init_metric() {
  local metric_name=$1

  cut_met=( $(echo $metric_name | sed -e "s/^RAD_//g" -e "s/^RADICA_//g" -e 's/'${sepm}'/ /g') )
  CAS=${cut_met[0]}
  SOUSCAS=${cut_met[1]}
  short_metric_name=${cut_met[2]}${sepm}${cut_met[3]}${sepm}${cut_met[4]}

  # Where are the reference (target) nc files and what is the prefix of the file?
  if [[ $(is_metric_rad) -eq 1 ]] ; then
    REF_DIR=$RAD
    tmp=$SOUSCAS
    SOUSCAS=${tmp:0:-3}
    TIME=${tmp: -3}
    short_metric_name=RAD-$short_metric_name
    PRE_FILE=RAD$TIME # TBD choisir CAS/SOUSCAS/RADTIME.nc ou CAS/SOUSCASTIME/RAD.nc
    if [[ $(is_metric_ica) -eq 1 ]] ; then
      PRE_FILE=*RAD$TIME # TBD choisir CAS/SOUSCAS/RADTIME.nc ou CAS/SOUSCASTIME/RAD.nc
    fi
  else
    REF_DIR=$LES
    PRE_FILE=SCM
  fi
}

function handle_one_metric() {
  local metric_name=$1

  echo "Computing Metric $metric_name"
  init_metric "$metric_name"

  ##################################
  # Compute reference mean and var
  # echo reference value and var
  echo "./get_one_metric_target_and_var.sh $metric_name $REF_DIR"
  ./get_one_metric_target_and_var.sh "$metric_name" "$REF_DIR" > "${REF_DIR}_$metric_name.csv"
  if [[ $? -ne 0 ]] ; then
    echo "error in $0: get_one_metric_target_and_var.sh failed"
    exit 1
  fi
  echo "Adding Metric $metric_name"
  add_to_metric_file "${REF_DIR}_$metric_name.csv" "$metrics_file_ref"

  #################################
  # Loop on files [CTRL/CAS/SOUSCAS/SCM.nc] WAVEi/CAS/SOUSCAS/<RADXXX|SCM>-$wave-*.nc
  list_dirs="$wavedir"
  if [[ "$REF_DIR" = "LES" && -d CTRL ]] ; then list_dirs="CTRL "$list_dirs ; fi

  for dir in $list_dirs ; do
    scm_dir=$dir/$CAS/$SOUSCAS/
    met_nam=${dir}_$metric_name
    met_fil=$met_nam.csv
    echo "SIM,$met_nam" > "$met_fil"
    for fil in $(ls $scm_dir/${PRE_FILE}*.nc); do
      echo "./get_one_metric_from_file.sh $fil $short_metric_name"
      met_val=$(./get_one_metric_from_file.sh "$fil" "$short_metric_name")
      if [[ $? -ne 0 ]] ; then met_val="" ; echo "On est la meme si Macron ne veut pas" ; exit 1 ; fi
      scm_nam=$(echo "$fil"|awk -F"/" '{ print $NF }'|sed -e "s/.nc//g")
      echo "$scm_nam,$met_val" >> "$met_fil"
    done # end loop $fil

    # add to metrics_file
    add_to_metric_file "$met_fil" "${wavedir}/metrics_${dir}_$wave.csv"

  done # end loop $dir
}

for metric_name in "${list_case[@]}"; do
  handle_one_metric "$metric_name"
done

### TBD check this
#delete simulations that didn't work in at least one case
for str in ",$" ",," "NaN" 
do
  res=$(grep $str "$wavedir/metrics_${wavedir}_${wave}.csv" | cut -c1-10)
  echo "res = $res"
  if [[ -n "${res}" ]] ;  then
    echo "delete simulations that didnt work in at least one case :"
    for sim in $(echo $res) ; do
      echo "$sim" >> "$wavedir/list_delsimu"
      sed_i "/$sim/d" "$wavedir/metrics_${wavedir}_${wave}.csv"
      sed_i "/$sim/d" "$wavedir/Par1D_Wave${wave}.asc"
    done
  fi
done
