#!/bin/bash

set -eu
#set -vx

. lmdz_env.sh
yr1=2001
yr2=2001
file_base=histmth
sim_d=$PWD
sim_=$( basename $sim_d )
echo $sim_ $sim_d



varse="aaa pourc_ter pourc_oce pourc_lic pourc_sic bils cldt flat LWdnSFC LWdnSFCclr LWupSFC ovap precip q2m rh2m rhum sens slp SWdnSFC SWdnSFCclr SWdnTOA SWupSFC SWupSFCclr SWupTOA SWupTOAclr t2m temp topl topl0 tsol vitu vitv vitw wind10m snow pr_lsc_i pr_lsc_l geop phis prw cldl cldm cldh cldt tops tops0 sols sols0 soll soll0"

varcmor="hfls hfss pr sfcWind rldscs rlds rlus rsdscs rsds rsuscs rsus rsutcs rsut rsdt rlut rlutcs sfcWind tas uas vas tasmax tasmin ts sst huss hurs tauu tauv psl zg500 hfns prw ta ua va wap hus pres hur oce ter sic lic clcalipso cltcalipso clhcalipso clmcalipso cllcalipso cll clm clh clt"
varcmor="hfls hfss pr sfcWind rldscs rlds rlus rsdscs rsds rsuscs rsus rsutcs rsut rsdt rlut rlutcs sfcWind tas huss hurs"

cmor=1
main_d=$root_dir
# ---------------------------------------------------------------------------------------------
# getting arguments
# ---------------------------------------------------------------------------------------------

while (($# > 0)); do
    case $1 in
       -h|--help) echo Use 1 : $0 [-cmor "var1 var2"] [-years YEAR1:YEAR2] 
                  echo Use 2 : $0 [-se "var1 var2"]  [-years YEAR1:YEAR2]
                  echo -root_dir : directory containing simulations
                  echo -years : either 2000 or 2000:2003
                  echo -sim : simulation directory ;;
       -cmor) cmor=1 ; varcmor="$2" ; shift 2  ;;
       -root_dir) main_d=$2 ; shift 2  ;;
       -years) yr1=$( echo $2 | cut -d: -f1 )
               yr2=$( echo $2 | cut -d: -f2 ) ; shift 2 ;;
       -se) cmor=0 ; varse="$2" ; shift 2 ;;
       -sim) sim_=$2 ; sim_d=$PWD/$sim_ ; shift 2 ;;
       *) bash seasonal_cycle.sh -h ; exit
    esac
done
echo $varcmor
echo yr1 $yr1
echo yr2 $yr2
if [ ! -d $main_d ] ; then echo Directory $main_d does not exist ; exit 1 ; fi

cd $sim_d
declare -A varo
declare -A fact

# ---------------------------------------------------------------------------------------------
function cmor_init { # cmor dictionary
# ---------------------------------------------------------------------------------------------
    echo varcmor $*
    varse=""
    for var_ in $* ; do
       echo var_ $var_
       fact[$var_]=1.
       case $var_ in
          hfls)    varo[$var_]=flat ; fact[$var_]=-1. ;;
          hfss)    varo[$var_]=sens ; fact[$var_]=-1. ;;
          pr)      varo[$var_]=precip ; echo MEME SI MACRON ;; 
          sfcWind) varo[$var_]=wind10m ;;
          rldscs)  varo[$var_]=LWdnSFCclr ;;
          rlds)    varo[$var_]=LWdnSFC ;;
          rlus)    varo[$var_]=LWupSFC ;;
          rsdscs)  varo[$var_]=SWdnSFCclr ;;
          rsds)    varo[$var_]=SWdnSFC ;;
          rsuscs)  varo[$var_]=SWupSFCclr ;;
          rsus)    varo[$var_]=SWupSFC ;;
          rsutcs)  varo[$var_]=SWupTOAclr ;;
          rsut)    varo[$var_]=SWupTOA ;;
          rsdt)    varo[$var_]=SWdnTOA ;;
          rlut)    varo[$var_]=topl ;;
          rlutcs)  varo[$var_]=topl0 ;;
          sfcWind) varo[$var_]=wind10m ;;
          tas)     varo[$var_]=t2m ;;
          uas)     varo[$var_]=u10m ;;
          vas)     varo[$var_]=v10m ;;
          tasmax)     varo[$var_]=ave_t2m_daily_max ;;
          tasmin)     varo[$var_]=ave_t2m_daily_min ;;
          ts)      varo[$var_]=tsol ;;
          sst)     varo[$var_]=tsol_oce ;;
          huss)    varo[$var_]=q2m ;;
          hurs)    varo[$var_]=rh2m ;;
          tauu)    varo[$var_]=taux_oce ;;
          tauv)    varo[$var_]=tauy_oce ;;
          psl)     varo[$var_]=slp ; fact[$var_]=0.01 ;;
          zg500)   varo[$var_]=z500 ;;
          hfns)    varo[$var_]=bils ;;
          prw)     varo[$var_]=prw ;;
          ta)      varo[$var_]=temp ;;
          ua)      varo[$var_]=vitu ;;
          va)      varo[$var_]=vitv ;;
          wap)     varo[$var_]=vitw ;;
          hus)     varo[$var_]=ovap ;;
          pres)    varo[$var_]=pres ;;
          hur)     varo[$var_]=rhum ; fact[$var_]=100. ;;
          oce)    varo[$var_]=pourc_oce ; fact[$var_]=0.01 ;;
          ter)    varo[$var_]=pourc_ter ; fact[$var_]=0.01 ;;
          sic)    varo[$var_]=pourc_sic ; fact[$var_]=0.01 ;;
          lic)    varo[$var_]=pourc_lic ; fact[$var_]=0.01 ;;
          clcalipso)    varo[$var_]=clcalipso ; fact[$var_]=100. ;;
          cltcalipso)    varo[$var_]=cltcalipso ; fact[$var_]=100. ;;
          clhcalipso)    varo[$var_]=clhcalipso ; fact[$var_]=100. ;;
          clmcalipso)    varo[$var_]=clmcalipso ; fact[$var_]=100. ;;
          cllcalipso)    varo[$var_]=cllcalipso ; fact[$var_]=100. ;;
          cll)     varo[$var_]=cldl ; fact[$var_]=100. ;;
          clm)     varo[$var_]=cldm ; fact[$var_]=100. ;;
          clh)     varo[$var_]=cldh ; fact[$var_]=100. ;;
          clt)     varo[$var_]=cldt ; fact[$var_]=100. ;;
          *)       varo[$var_]=$var_
       esac
       echo APRES var ${varo[$var_]}
       varse="$varse ${varo[$var_]}"
    done
}
# -----------------------------------------------------------------------

if [ $cmor = 1 ] ; then cmor_init $varcmor ; fi
echo varse $varse


# Liste des fichiers disponibles entre les annees yr1 et yr2
# ----------------------------------------------------------
echo $yr1 $yr2
#echo $( echo $yr1 | wc -c )
if [ $( echo $yr1 | wc -c ) -ge 6 ] ; then
   if [ $yr2 != $yr1 ] ; then
       echo Not possible to run with monthly files on more than one month so far ; exit 1
   fi
fi

files=$( for yr in $( seq $yr1 $yr2 ) ; do ls $file_base.${yr}*.nc ; done )
echo Liste des fichiers traites : $files

# Construction de la liste des variables disponibles
# --------------------------------------------------
var_list_o=$varse
for file_ in $files ; do
   # Recuperation de la liste des variables dans le fichier
       #ncdump -h $file_ | grep long_name | cut -d: -f1
       var_list_=$( ncdump -h $file_ | grep long_name | cut -d: -f1 )
   # Liste des variables contenues soit dans le fichier soit dans $var_list_o
       var_list_n=$( ( for var in $var_list_o $var_list_ ; do echo $var ; done ) | sort | uniq -i -d )
   # Liste des suprimees
       echo Liste des variables non disponibles dans $file_ : $( ( for var in $var_list_o $var_list_n ; do echo $var ; done ) | sort | uniq -i -u )
       var_list_o=$var_list_n
done

echo Liste des variables traitees : $var_list_o
vars="-selvar" ; for var_ in $var_list_n ; do vars="$vars,$var_" ; done

# --------------------------------------------------------------------
# Extracting variables in the original individual files
# --------------------------------------------------------------------

for file_ in $files ; do
    # Extraction des variables
       tmpf=tmp.$file_
       \rm -f $tmpf
       cdo $vars $file_ $tmpf
    # Correction calendrier à 360d. Corrige depuis 2017
       cal=`ncdump -h $tmpf | grep time_counter | grep calendar | cut -d\" -f2`
       if [ "$cal"  = "360d" ] ; then ncatted -a calendar,"time_counter",o,c,"360_day" -O $tmpf ; fi
done


# --------------------------------------------------------------------
# Merging files & extracting the mean seasonal cycle of required variables
# --------------------------------------------------------------------

if [ $cmor = 1 ] ; then
    se_d=$main_d/CMOR/${sim_}_${yr1}_${yr2}
else
    se_d=$main_d/SE
fi
mkdir -p $se_d
file_se=$se_d/${file_base}.${yr1}-${yr2}.nc
\rm -rf $se_d/$file_se
cdo ymonmean -mergetime $( for f_ in $files ; do echo tmp.$f_ ; done )  $file_se

# --------------------------------------------------------------------
# From histmth to cmor
# --------------------------------------------------------------------
echo varcmor $varcmor
if [ $cmor = 1 ] ; then
    for var_ in $varcmor ; do
          varo_=${varo[$var_]}
          fact_=${fact[$var_]}
          set +e
        # Checking variable availability
          cdo info -selvar,$varo_ $file_se > /dev/null 2>&1
          status_=$?
          set -e
          if [ $status_ != 0 ] ; then
             echo variable $varo_ non disponible dans le fichier $file_se
          else
             echo var_ existe $var_
             if [ $fact_ = 1. ]; then
                if [ $var_ == ta ] || [ $var_ == ua ] || [ $var_ == va ] || [ $var_ == wap ] || [ $var_ == hus ] || [ $var_ == hur ]; then
                 opt="selvar,$varo_,pres"
                else
                 opt="selvar,$varo_"
                fi
             else
                opt="mulc,$fact_ -selvar,$varo_"
             fi
             outfile=$se_d/$var_.nc ; \rm -f $outfile
             cdo $opt $file_se $outfile
             if [ $var_ != $varo_ ]; then
               ncrename -v $varo_,$var_ ${outfile}
             fi
          fi
    done
    \rm -f $file_se
fi


