#!/bin/ksh
#
#   script to  get and transform to netcdf initial and clim files for osm run
#   Emanuel Dutra, November 2017

set -exu

mkdir -p $FIXDIR 


WDIR=$TMPDIR/create_init_clim  # Work directory 
mkdir -p $WDIR 
cd $WDIR 
rm -rfv 

if [[ ! -r $FORCRAW/fix.tar.gz ]]; then

  ## 1. Monthly Albedo and LAI 
  ## a. monthly 
  rm -f month_alnid month_aluvd month_lai_lv month_lai_hv tmp.grb 
  for im in 01 02 03 04 05 06 07 08 09 10 11 12
  do
    for sn in alnid aluvd lai_lv lai_hv
    do
      grib_copy -w shortName=$sn $CLIMATE_DIR/ICMCL-${im} tmp.grb 
      cat tmp.grb >> month_${sn}
      rm -f tmp.grb 
    done
  done

  # Compute total broadband albedo
  cdo -add -mulc,0.45976 month_aluvd -mulc,0.54024 month_alnid month_alb 
  grib_set -s shortName=al month_alb tmp.grb ; mv tmp.grb month_alb 

  rm -f clim.grb 
  cat month_alb > clim.grb 
  cat month_lai_lv >> clim.grb 
  cat month_lai_hv >> clim.grb 

  # b . static from from initial conditions
  grib_copy -w shortName=lsm/sr/sdor/lsrh/z/slt/cvl/cvh/tvl/tvh $ICMGG00CLM tmp.grb 
  cat tmp.grb >> clim.grb 

  cat $ICMGG00Z >> clim.grb 
  
  cat $ECINIT/climate/bare_soil_albedos.grb >> clim.grb 

  ##=================================================
  ## 2. Initial conditions 
    # From experiment 
  grib_copy -w shortName=swvl1/swvl2/swvl3/swvl4/stl1/stl2/stl3/stl4/skt/asn/rsn/sd/tsn $ICMGG00 init.grb 
  

  ##============================================
  ## convert to netcdf 

python << EOF
from init_clim import *
from pyfunc import *

FCLIMgrb='clim.grb'
FINITgrb='init.grb'

## Generate netcdf files (empty)
ginfo = get_grib_grid(FCLIMgrb,retbounds=True) 
gen_file(FOUT='surfclim_all',FTYPE='clm',ginfo=ginfo,nlevs=${NCSS:-4})
gen_file(FOUT='soilinit_all',FTYPE='ini',ginfo=ginfo,nlevs=${NCSS:-4})

## Convert grib to netcdf 
grib2nc(FNC='surfclim_all',FGRB=FCLIMgrb)
grib2nc(FNC='soilinit_all',FGRB=FINITgrb)

### Defaults defining points 
LLAND=True
LLAKE=False
LOCEAN=False
BBOX=[-190,190,-91,91]

## find mask, i.e. point where we'll ran the model 
mask = get_mask('surfclim_all',LLAND,LLAKE,LOCEAN,BBOX)

## Create final files cutting down mask 
cut_mask(mask=mask,FIN='surfclim_all',FOUT='surfclim')
cut_mask(mask=mask,FIN='soilinit_all',FOUT='soilinit')
## finally set Mask to 1 
nc = Dataset('surfclim','r+')
nc.variables['Mask'][:] = 1
nc.close()
EOF

  ## save data:
  cp -f clim.grb init.grb soilinit surfclim surfclim_all soilinit_all $FIXDIR
  tar -cvf fix.tar clim.grb init.grb soilinit surfclim surfclim_all soilinit_all
  gzip fix.tar 
  cp fix.tar.gz $FORCRAW/

else
  tar -zxvf $FORCRAW/fix.tar.gz
fi 
cp -f clim.grb init.grb soilinit surfclim surfclim_all soilinit_all $FIXDIR

rm -rfv $WDIR  
# exit 0 
# 

 
