#!/bin/bash
# Shell script to split variables from a LMDZ output and give the right time-axis values
# L. Fita, LMD. March 2015

# input folder
infold=.

# output folder
outfold=.

# intput file
infile=NPv5.12a_SE_1981_1983_1M_histmth.nc

# Location of the python scripts
HOMEpy=/home/lfita/etudes/WRF_LMDZ/svn/LMD_WRF/tools

# Time variables' name
tnames='time_centered:time_instant'

# Variables not to change
NOvars='time_counter:time_counter_bnds:lon:lat:presnivs'

### END of MODIFICATIONS ###
####### ###### ##### #### ### ## #
timedim='time_counter'

function isin_list() {
# Function to check whether a value is in a list
  list=$1
  value=$2

  is=`echo ${list} | tr ':' '\n' | awk '{print "@"$1"@"}' | grep '@'${value}'@' | wc -w`
  if test ${is} -eq 1
  then
    true
  else
    false
  fi
}


#######    #######
## MAIN
    #######

Linfile=`expr length ${infile}`
Linfile3=`expr $Linfile - 3`
headfile=${infile:0:Linfile3}

ifile=${infold}/${infile}

# Cleaning original file from accents in the attributes
python ${HOMEpy}/nc_var.py -o varrmattr -S long_name -f ${ifile} -v random_notrig
python ${HOMEpy}/nc_var.py -o varrmattr -S long_name -f ${ifile} -v proba_notrig
python ${HOMEpy}/nc_var.py -o varaddattr -S 'long_name|Tirage!aleatoire!de!non-declanchement' \
 -v random_notrig -f ${ifile} 
python ${HOMEpy}/nc_var.py -o varaddattr -S 'long_name|Probabilite!de!non-declanchement' \
 -v proba_notrig -f ${ifile} 

# Preparing time variables values
tns=`echo ${tnames} | tr ':' ' '`
for tn in ${tns}; do
  python ${HOMEpy}/nc_var.py -o varout -f ${ifile} -S ${timedim}:-1 -v ${tn} |       \
    awk '{print $2}' >& ${tn}.dat
done

# Getting all variables in the file
allvariables=`python ${HOMEpy}/nc_var.py -o ivars -f ${ifile} | grep allvars |       \
   awk '{print $3}'`

allvars=` echo ${allvariables} | tr ':' ' '`
for var in ${allvars}; do
  if ! $(isin_list ${NOvars} ${var}); then
    vfile=${headfile}_${var}.nc
    vmfile=${headfile}_${var}mean.nc

# Which time_coordinate
    coord=`python ${HOMEpy}/nc_var.py -o ivattrs -f ${ifile} -v ${var} | grep -v '#' \
      | grep coordinates | awk '{print $3}'`
# Working in that variables which have an attribute called 'coordinates' wich content
#   any of the tnames on the original file, CDO remove this attribute...
    Lcoord=`expr length ${coord}'0'`
    if test ${Lcoord} -gt 1 && test ! -f ${vmfile}; then
      timevar=`echo ${coord} | tr '!' ' ' | awk '{print $1}'`
      echo "  "${var}" time variable:"${timevar}"..."

      tunits=`python ${HOMEpy}/nc_var.py -o ivattrs -f ${ifile} -v ${timevar} |      \
        grep -v '#' | grep units | awk '{print $3}'`
      tcal=`python ${HOMEpy}/nc_var.py -o ivattrs -f ${ifile} -v ${timevar} |        \
        grep -v '#' | grep calendar | awk '{print $3}'`

# Individual variable file
      cdo selvar,${var} ${ifile} ${vfile}
# Changing variable names 
      python ${HOMEpy}/nc_var.py -o chvarname -S ${timevar} -f ${vfile} -v ${timedim}
# Adding values to the file
      python ${HOMEpy}/nc_var.py -o setvar_asciivalues -S ${timevar}.dat -f          \
        ${vfile} -v ${timevar}
# Adding attributes
      python ${HOMEpy}/nc_var.py -o varaddattr -S 'standard_name|time' -v ${timevar} \
        -f ${vfile}
      python ${HOMEpy}/nc_var.py -o varaddattr -S 'long_name|time' -v ${timevar} -f  \
        ${vfile}
      python ${HOMEpy}/nc_var.py -o varaddattr -S 'units|'${tunits} -v ${timevar} -f \
        ${vfile}
      python ${HOMEpy}/nc_var.py -o varaddattr -S 'calendar|'${tcal} -v ${timevar} -f\
        ${vfile}
      python ${HOMEpy}/nc_var.py -o varaddattr -S 'coordinates|'${timevar}'!lat!lon' -v \
        ${var} -f ${vfile}

      if test -f ${vmfile}; then rm ${vmfile}; fi
      cdo seasmean ${vfile} ${vmfile}
#      exit
    fi
  fi
done
