#!/bin/bash
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# This script combines and formates the forcing solid and liquid 
# precipitation fields. output_step12_0h.nc and output_step12_12h.nc as 
# described in README should be in the working directory 
#
# History : Virginie Guemas - Initial version                         - 2012 
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#                                Arguments
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
year='2013'
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ncap2 -O -s "sf=double(sf)" output_step12_12h.nc output_step12_12h.nc
ncap2 -O -s "tp=double(tp)" output_step12_12h.nc output_step12_12h.nc
ncap2 -O -s "sf=double(sf)" output_step12_0h.nc output_step12_0h.nc
ncap2 -O -s "tp=double(tp)" output_step12_0h.nc output_step12_0h.nc
ncatted -O -a add_offset,sf,d,d, output_step12_0h.nc output_step12_0h.nc
ncatted -O -a add_offset,tp,d,d, output_step12_0h.nc output_step12_0h.nc
ncatted -O -a scale_factor,tp,d,d, output_step12_0h.nc output_step12_0h.nc
ncatted -O -a scale_factor,sf,d,d, output_step12_0h.nc output_step12_0h.nc
ncatted -O -a add_offset,sf,d,d, output_step12_12h.nc output_step12_12h.nc
ncatted -O -a add_offset,tp,d,d, output_step12_12h.nc output_step12_12h.nc
ncatted -O -a scale_factor,sf,d,d, output_step12_12h.nc output_step12_12h.nc
ncatted -O -a scale_factor,tp,d,d, output_step12_12h.nc output_step12_12h.nc
cdo add output_step12_12h.nc output_step12_0h.nc output_sf_tp_int.nc
cdo divc,86.4 output_sf_tp_int.nc  output_sf_tp.nc
ncks -v sf output_sf_tp.nc snow_eraint_int.nc
ncrename -v sf,snow snow_eraint_int.nc
ncks -v tp output_sf_tp.nc precip_eraint_int.nc
ncrename -v tp,precip precip_eraint_int.nc
cdo shifttime,14day precip_eraint_int.nc precip_eraint_${year}.nc
cdo shifttime,14day snow_eraint_int.nc snow_eraint_${year}.nc
rm -f output_step12_0h.nc output_step12_12h.nc output_sf_tp_int.nc output_sf_tp.nc snow_eraint_int.nc precip_eraint_int.nc
