#!/bin/bash

set -vx
force_create=1

comp=$1 
local=`pwd`

for season in YEAR DJF JJA ; do


cd $local

if [ "$season" = "YEAR" ] ; then
   masks="ter oce NAtl Arct circA otrop glob eto weak conv subs NH SH"
   mask_figs="NAtl Arct circA glob ter oce otrop interH etoa circAa NAtla conv weak subs"
else
   masks="NAtl Arct circA Sibe USA"
   mask_figs="NAtl Arct circA Sibe USA"
fi

WRK_D=$local/XMGR$$/$season
if [ -d $WRK_D ] ; then WRK_D=$WRK_D$$ ; fi
mkdir -p $WRK_D
cd $WRK_D
ln -s ../../mas*nc .

comp=`basename $1`
if [ -d /prodigfs/ipslfs/dods/fabric/lmdz/MultiSimu ] ; then
   # Installation multi modele fabric
   COMP_D=/prodigfs/ipslfs/dods/fabric/lmdz/MultiSimu/$comp
   CMOR_DIR=/prodigfs/ipslfs/dods/fabric/lmdz/VLR/$season
elif [ "$comp" = "$1" ] ; then
   # Installation locale
   COMP_D=.
   CMOR_DIR=.
else
   # Path absolu
   COMP_D=$1
   CMOR_DIR=.
fi

###############################################
# Liste des simulations de la comparasion $comp
listsims="" ; listsimsy=""
DEF_FILE=$COMP_D/def.txt ; if [ ! -f "$DEF_FILE" ] ; then renseigner $DEF_FILE ; exit ; fi
for s in `awk ' {print $1"_"$2 } ' $DEF_FILE` ; do listsimsy="$listsimsy $s" ; done
for s in `awk ' {print $1 } ' $DEF_FILE` ; do listsims="$listsims $s" ; done
###############################################

echo $listsimsy
ici=`pwd`

for simy in  OBS $listsimsy ; do
  sim=`echo $simy | sed -e 's/_[0-9][0-9][0-9][0-9]_[0-9][0-9][0-9][0-9]//'`
  years=`echo $simy | sed -e s/${sim}//`
  echo SIM $sim
  echo years $years


  SIM_DIR=$CMOR_DIR/$GR/$sim$years
ETOA_DIR=$SIM_DIR/METRICS


   for mask in $masks ; do
#      mkdir -p XMGR$$/$mask
     xmgr=$ETOA_DIR/$mask
     mkdir -p $ETOA_DIR
     if [ ! -f "$xmgr" -o "$force_create" = "1" ] ; then
        \rm -f $xmgr ; touch $xmgr
        if [ ! -d $SIM_DIR ] ; then echo $SIM_DIR absent ; exit ; fi
        set +e ; \rm resu$sim ; set -e
        for var in rsut clhcalipso cllcalipso clmcalipso cltcalipso clt hfls hfss hurs huss pr ts tas sst psl rldscs rlds rlus rlutcs rlut rsdscs rsds rsdt rsuscs rsus rsutcs prw ; do
          if [ -f "$SIM_DIR/NC/$var.nc" ] ; then
           if [ "$mask" = "glob" ] ; then
              val=`cdo output -fldmean -selvar,$var $SIM_DIR/NC/$var.nc`
           elif [ ! -f "mask$mask.nc" ] ; then
               echo Le fichier mask$mask.nc n existe pas ; exit
           else
             if [ 1 = 1 ] ; then
              if [ 1 = 0 && $var = "hfls" ] && [ $simy == "OBS" ]; then
               cdo remapcon,mask$mask.nc $SIM_DIR/NC/$var.nc_ocean-only tmp.nc
               val=`cdo output -fldmean -selvar,$var -mul tmp.nc mask$mask.nc`
              else
               cdo remapcon,mask$mask.nc $SIM_DIR/NC/$var.nc tmp.nc
               val=`cdo output -fldmean -selvar,$var -mul tmp.nc mask$mask.nc`
              fi
             else
              cdo remapcon,maskotrop.nc $SIM_DIR/NC/$var.nc tmp.nc
              cdo remapcon,maskotrop.nc mask$mask.nc mask.nc
              val=`cdo output -fldmean -selvar,$var -mul tmp.nc mask.nc`
             fi
           fi
           echo $mask  $sim $var $val
           echo $var $val >> $xmgr
          else
            echo $var 999999 >> $xmgr
          fi
        done
      rsut=`grep '^rsut ' $xmgr | awk ' { print $2 } '`
      rsutcs=`grep '^rsutcs ' $xmgr | awk ' { print $2 } '`
      rlut=`grep '^rlut ' $xmgr | awk ' { print $2 } '`
      rlutcs=`grep '^rlutcs ' $xmgr | awk ' { print $2 } '`
      hfls=`grep '^hfls ' $xmgr | awk ' { print $2 } '`
      hfss=`grep '^hfss ' $xmgr | awk ' { print $2 } '`
      rlds=`grep '^rlds ' $xmgr | awk ' { print $2 } '`
      rldscs=`grep '^rldscs ' $xmgr | awk ' { print $2 } '`
      rsds=`grep '^rsds ' $xmgr | awk ' { print $2 } '`
      rsdscs=`grep '^rsdscs ' $xmgr | awk ' { print $2 } '`
      rlus=`grep '^rlus ' $xmgr | awk ' { print $2 } '`
      rsus=`grep '^rsus ' $xmgr | awk ' { print $2 } '`
      rsuscs=`grep '^rsuscs ' $xmgr | awk ' { print $2 } '`
      rsdt=`grep '^rsdt ' $xmgr | awk ' { print $2 } '`
      echo $rsut $rsutcs | awk ' { print "crest" , $2 - $1 } ' >> $xmgr
      echo $rlut $rlutcs | awk ' { print "crelt" , $2 - $1 } ' >> $xmgr
      echo $rsut $rsutcs $rlut $rlutcs | awk ' { print "cret"  , $2 - $1 +$4 -$3 } ' >> $xmgr
      echo $rsdt $rsut | awk ' { print "rst"  , $1 - $2 } ' >> $xmgr
      echo $rsdt $rsutcs | awk ' { print "rstcs"  , $1 - $2 } ' >> $xmgr
      echo $rsdt $rsut $rlut | awk ' { print "rt"  , $1 - $2 -$3 } ' >> $xmgr
      echo $hfls $hfss   | awk ' { print "trbs"  , $1 + $2 } ' >> $xmgr
      echo $rlds $rlus   | awk ' { print "rls"  , $1 - $2 } ' >> $xmgr
      echo $rsds $rsus   | awk ' { print "rss"  , $1 - $2 } ' >> $xmgr
      echo $rlds $rlus $rsds $rsus  | awk ' { print "rs"   , $1 - $2 +$3 - $4 } ' >> $xmgr
      echo $rlds $rldscs $rsds $rsdscs $rsus $rsuscs | awk ' { print "cres"   , $1 - $2 + $3 - $4 - $5 + $6 } ' >> $xmgr
      echo $rlds $rldscs $rsds $rsdscs $rsus $rsuscs $hfls | awk ' { print "crehfls"   , $1 - $2 + $3 - $4 - $5 + $6 - $7 } ' >> $xmgr
      echo $rlds $rlus $rsds $rsus  $hfls $hfss   | awk ' { print "bils"  , $1 - $2 + $3 - $4 - $5 - $6 } ' >> $xmgr
      fi
   done
   
   # Masques combinés
   set +e
   paste $ETOA_DIR/otrop $ETOA_DIR/eto | awk ' { if ( $2 == 999999 || $4 == 999999 ) print $1 , 999999 ; else print $1 , $4 - $2 } ' >| $ETOA_DIR/etoa
   paste $ETOA_DIR/circA $ETOA_DIR/otrop | awk ' { if ( $2 == 999999 || $4 == 999999 ) print $1 , 999999 ; else print $1 , $4 - $2 } ' >| $ETOA_DIR/circAa
   paste $ETOA_DIR/NAtl $ETOA_DIR/otrop | awk ' { if ( $2 == 999999 || $4 == 999999 ) print $1 , 999999 ; else print $1 , $4 - $2 } ' >| $ETOA_DIR/NAtla
   paste $ETOA_DIR/SH $ETOA_DIR/NH | awk ' { if ( $2 == 999999 || $4 == 999999 ) print $1 , 999999 ; else print $1 , $4 - $2 } ' >| $ETOA_DIR/interH
   set -e

done


#########################################################################################
# Tracers
#########################################################################################



cat <<eod>| descr
clhcalipso  1  High Clouds
cllcalipso  1  Low Clouds
clmcalipso  1  Mid Clouds
cltcalipso  1  Total Clouds
clt         1  LMDZ Total Clouds
hfls       -1  -LE
hfss       -1  -H
hurs        1  RHsrf
huss        1 Surface specific humidity
pr         10  PR*10
prw         1  PRW
psl         1  SLP
ts         10  Ts*10
sst        10  sst*10
tas        10  T2m*10
rlds        1  LWdn srf
rldscs      1  LWdn srf Clr
rlus       -1  LWup Srf
rlutcs     -1  LW TOA Clr
rlut       -1  LW TOA
rsdscs      1  SWdn srf Clr
rsds        1  SWdn srf
rsdt        1  SWdn TOA
rsuscs     -1  SWup srf Clr
rsus       -1  SWup srf
rsutcs     -1  SW TOA Clr
rstcs      -1  SW TOA Clr
rsut       -1  SW TOA
crest       1  SW CRE TOA
crelt       1  LW CRE TOA
cres        1  CRE srf
crehfls     1  CRE - LE
cret        1  CRE TOA
rst         1  SW TOA
rt          1  SW+LW TOA
trbs       -1  -(LE+H)
rls         1  LW srf
rss         1  SW srf
rs          1  SW+LW srf
bils        1  Srf budget
eod

# -------------------  debut boucle sur les figures ----------------------------
for mask in $mask_figs ; do
# -------------------  debut boucle sur les figures ----------------------------

   case $mask in
       NAtla|circAa|etoa|oce|otrop) listevars="ts bils crehfls cres rs rss crest hfls tas cllcalipso clhcalipso " ;;
       interH|glob|ter|NAtl|circA|conv|weak|subs) listevars="bils tas rt rlutcs crelt rsutcs crest cllcalipso clmcalipso clhcalipso pr" ;;
       Arct|Sibe|USA) listevars="tas rs rlds rsds crelt crest cllcalipso clmcalipso clhcalipso pr prw" ;;
       *) echo cas non prevu ; exit
   esac

   nvars=`echo $listevars | wc -w | awk ' { print $1 } '`
   case $mask in
     NAtl) yax="North Atlantic " ;;
     Arct) yax="Arctic ocean" ;;
     circA) yax="Circum Antartica " ;;
     Sibe) yax="Siberia " ;;
     USA) yax="US Gr. Plains " ;;
     glob) yax="Global " ;;
     ter) yax="Land " ;;
     oce) yax="Ocean " ;;
     otrop) yax="Tropical ocean " ;;
     interH) yax="Inter Hemispheric " ;;
     etoa) yax="ETOA " ;;
     circAa) yax="Circum Antartic Anom. " ;;
     NAtla) yax="Nort Atlantic Anom. " ;;
     conv) yax="Convective regimes " ;;
     weak) yax="Weak convection " ;;
     subs) yax="Subsidences "
   esac
   cat <<...eod>| tmp.param
    g0 type Chart
    world -0.5, -35, $nvars, 35
    yaxis  label "$yax Fluxes (W/m2) "
    xaxis  ticklabel font 0
    xaxis  ticklabel color 1
    xaxis  tick place both
    xaxis  tick spec type both
    xaxis  tick spec 11
    xaxis  ticklabel char size 1.3
    xaxis  ticklabel angle 90
    yaxis  tick major 10
    yaxis  tick minor ticks 1
    legend 1.20, 0.8
...eod

   ii=0
   for var in $listevars ; do
      fact=`grep "^$var " descr | awk ' { print $2 } '`
      titre=`grep "^$var " descr | sed -e 's/'$var'//' -e 's/'$fact'//'`
      cat <<......eod>> tmp.param
      xaxis  tick major $ii, $ii
      xaxis  ticklabel $ii, "$titre"
......eod
      (( ii = $ii + 1 ))
   done


   prev=""
   ip=0
   listex=""
   echo LISTESIMSY $listsimsy
   for simy in $listsimsy ; do
      sim=`echo $simy | sed -e 's/_[0-9][0-9][0-9][0-9]_[0-9][0-9][0-9][0-9]//'`
      years=`echo $simy | sed -e s/${sim}//`
      echo $sim
      SIM_DIR=$CMOR_DIR/$sim$years/METRICS
      ls $SIM_DIR
      OBS_DIR=$CMOR_DIR/OBS/METRICS
      mkdir -p $WRK_D/$mask
      if [ "$sim" = "$prev" ] ; then # Cas ou on a plusieurs decennies de la meme simu
         (( ip = $ip + 1 ))
         xmgr=$WRK_D/$mask/$sim.$ip
         listex="$listex $sim.$ip"
      else
         xmgr=$WRK_D/$mask/$sim 
         ip=0 ; prev=$sim
         listex="$listex $sim"
      fi
      rm -f $xmgr ; touch $xmgr
      for var in $listevars ; do
         echo var $var
         fact=`grep "^$var " descr | awk ' { print $2 } '`
         paste $OBS_DIR/$mask $SIM_DIR/$mask | grep "^$var " | awk ' { if ( $4 == 999999 ) print 0 ; else print '$fact' * ( $4 - $2 ) } ' >> $xmgr
      done
   done
         


   size=`echo $listsims | wc -w | awk ' { print 3. / $1 } '`
   for ii in 0 1 2 3 4 5 6 7 8 9 10 11 12 ; do
      echo "s$ii type bar" >> tmp.param
      echo "s$ii symbol fill pattern 1" >> tmp.param
      echo "s$ii symbol size $size" >> tmp.param
      echo "s$ii line linestyle 0" >> tmp.param
   done

   cd $WRK_D/$mask
   pwd ; echo xmgrace $listex -param ../../../tmp.param -legend load -hardcopy -hdevice EPS -printfile tmp.eps
   xmgrace $listex -param ../../../tmp.param -legend load -hardcopy -hdevice EPS -printfile tmp.eps
   epstopdf tmp.eps
   OUT_D=$COMP_D/METRICS/$season ; mkdir -p $OUT_D
   \mv -f tmp.pdf $OUT_D/$mask.pdf ; convert -density 144 $OUT_D/$mask.pdf $OUT_D/$mask.png
   cd ../../..

done

cp mask*png $OUT_D
done
