#!/bin/bash

#set -vx

local=`pwd -P`
cd $local

####################################################################
# Frederic Hourdin. 2015/09/07
# Script de pseudo Cmorisation (passage au format CMIP des sorties
# du modele.
####################################################################

####################################################################
# Defaults :
####################################################################
login=`whoami`

hostname=`hostname`
if [ ${hostname:0:5} = cicla ] ; then
DODSDIR=/thredds/ipsl
OBSDIR=$DODSDIR/fabric/lmdz/SE/CMOR/OBS
fi
if [ ${hostname:0:5} = camel ] ; then
DODSDIR=/thredds/ipsl
OBSDIR=$DODSDIR/fabric/lmdz/SE/CMOR/OBS
fi
if [ ${hostname:0:5} = irene ] ; then
DODSDIR=
OBSDIR=
fi
if [ ${hostname:0:5} = jean- ] ; then
DODSDIR=
OBSDIR=
fi

runstxt=${local}/runs.txt
while test -n "${1}"; do
   case $1 in
      "-runsfile") runstxt=$2 ; shift ;;
      *) comp=$1 ;;
   esac
   shift
done

MainDIR=$DODSDIR/$login/lmdz/SE
INDIR=$DODSDIR/$login/lmdz/SE/ORIG
COMP_D=$DODSDIR/$login/lmdz/MultiSimu/$comp

if [ ! -f $COMP_D/def.txt ] ; then
    echo comparaison multi modele $COMP_D non prevue
    exit
fi
if [ ! -f $runstxt ] ; then
    echo Fichier listant les simulations inexistants
    exit
fi

WRK=$MainDIR/WORK/CMOR

i=1
while [ "`ps -ux | grep cmor.sh | grep bin | wc -l`" != "2" ] ; do
   echo Mise en attente de cmor.sh deja en cours d execution $i
   sleep 2 ; (( i = $i + 1 ))
   if [ "$i" = "3600" ] ; then exit ; fi
done


####################################################################
# Interactive options
####################################################################
force_create=0 # if = 0/1, the existing files are not / are reprocessed
listevar="sfcWind,hfls,hfss,huss,hurs,pr,rldscs,rlds,rlus,rsdscs,rsds,rsuscs,rsus,rsutcs,rsut,rlut,rlutcs,rsdt,sfcWind,tas,ts,sst,tauu,tauv,psl,hfns,ta,ua,va,wap,hus,hur,clcalipso,cllcalipso,clmcalipso,clhcalipso,cltcalipso,clt,prw,cll,clm,clh,tasmax,tasmin,uas,vas"
listevar="sfcWind,hfls,hfss,huss,hurs,pr,rldscs,rlds,rlus,rsdscs,rsds,rsuscs,rsus,rsutcs,rsut,rlut,rlutcs,rsdt,sfcWind,tas,ts,sst,tauu,tauv,psl,zg500,hfns,ta,ua,va,wap,hus,hur,clcalipso,cllcalipso,clmcalipso,clhcalipso,cltcalipso,clt,prw,cll,clm,clh,tasmax,tasmin,uas,vas"
#listevar="psl"

ulimit -s unlimited
\rm -rf $WRK ; mkdir -p $WRK ; touch out$$

################################################################################
# Loop on avaliable simulations
################################################################################

cd $INDIR
#for file in *_histmth.nc ; do

for SE in `awk ' { print $1"_SE_"$2 } ' $COMP_D/def.txt` ; do
  sim=`echo $SE | sed -e 's/_SE_/ /' | awk ' { print $1 } '`
  years=`echo $SE | sed -e 's/_SE_/ /' | awk ' { print $2 } '`
  echo SEsim $SE $sim
  simdir=`grep -w "^$sim " $runstxt | awk ' { print $2 } '`
  simorig=`basename $simdir`
  echo SEsim simorig $simorig
  echo SEsim basename $simdir
  file=$simdir/ATM/Analyse/SE/${simorig}_SE_${years}_1M_histmth.nc
  if [ ! -f $file ] ; then
      echo PB fichier $file inexistant
    file=$INDIR/${simorig}_SE_${years}_1M_histmth.nc
    echo $file
  fi
  if [ -f $file ] ; then
   file=$INDIR/${simorig}_SE_${years}_1M_histmth.nc
   echo $file
   echo FILE $file
   cd $WRK
   dirout=$MainDIR/CMOR/${sim}_${years}/$cas
   echo $sim $years $dirout

   echo SEsim $dirout
   mkdir -p  $dirout

   for var in `echo $listevar | sed -e 's/,/ /g'` ; do

     case $var in
        clcalipso|cltcalipso|clhcalipso|clmcalipso|cllcalipso) filei=`echo $file | sed -e 's/histmth/histmthCOSP/'` ;;
        *) filei=$file
     esac

     if [ -f "$filei" ] ; then

       fact=1.
       case $var in
          hfls)    varo=flat ; fact=-1. ;;
          hfss)    varo=sens ; fact=-1. ;;
          pr)      varo=precip ;;
          sfcWind) varo=wind10m ;;
          rldscs)  varo=LWdnSFCclr ;;
          rlds)    varo=LWdnSFC ;;
          rlus)    varo=LWupSFC ;;
          rsdscs)  varo=SWdnSFCclr ;;
          rsds)    varo=SWdnSFC ;;
          rsuscs)  varo=SWupSFCclr ;;
          rsus)    varo=SWupSFC ;;
          rsutcs)  varo=SWupTOAclr ;;
          rsut)    varo=SWupTOA ;;
          rsdt)    varo=SWdnTOA ;;
          rlut)    varo=topl ;;
          rlutcs)  varo=topl0 ;;
          sfcWind) varo=wind10m ;;
          tas)     varo=t2m ;;
          uas)     varo=u10m ;;
          vas)     varo=v10m ;;
          tasmax)     varo=ave_t2m_daily_max ;;
          tasmin)     varo=ave_t2m_daily_min ;;
          ts)      varo=tsol ;;
          sst)     varo=tsol_oce ;;
          huss)    varo=q2m ;;
          hurs)    varo=rh2m ;;
          tauu)    varo=taux_oce ;;
          tauv)    varo=tauy_oce ;;
          psl)     varo=slp ; fact=0.01 ;;
          zg500)   varo=z500 ;;
          hfns)    varo=bils ;;
          prw)     varo=prw ;;
          ta)      varo=temp ;;
          ua)      varo=vitu ;;
          va)      varo=vitv ;;
          wap)     varo=vitw ;;
          hus)     varo=ovap ;;
          hur)     varo=rhum ; fact=100. ;;
          clcalipso)    varo=clcalipso ; fact=100. ;;
          cltcalipso)    varo=cltcalipso ; fact=100. ;;
          clhcalipso)    varo=clhcalipso ; fact=100. ;;
          clmcalipso)    varo=clmcalipso ; fact=100. ;;
          cllcalipso)    varo=cllcalipso ; fact=100. ;;
          cll)     varo=cldl ; fact=100. ;;
          clm)     varo=cldm ; fact=100. ;;
          clh)     varo=cldh ; fact=100. ;;
          clt)     varo=cldt ; fact=100. ;;
          *) echo "var $var non prevu" ; exit
       esac

       outfile=$dirout/$var.nc
       #echo `pwd`/$outfile
       if [ $force_create = 1 ] ; then rm -f $outfile ; fi
       if [ ! -f $outfile ] ; then
          \rm -f tmp.nc tmp1.nc
          if [ $fact = 1. ]; then
            opt="selvar,$varo"
          else
            opt="mulc,$fact -selvar,$varo"
          fi
          echo cdo $opt $filei tmp.nc
          cdo $opt $filei tmp.nc >> out$$
          if [ $var != $varo ]; then
            echo ncrename -v $varo,$var tmp.nc -O tmp1.nc 
            ncrename -v $varo,$var tmp.nc -O tmp1.nc  >> out$$
          else
            mv tmp.nc tmp1.nc
          fi
          if [ ! -f tmp1.nc ] ; then
              echo echec $years $var
          else
              \mv -f tmp1.nc $outfile
          fi
       fi
     fi # -f $filei
  done
 fi
done
