#!/bin/bash
# -----------------------------------------------------------------
# Description: Short script to merge atmospheric intial conditions
#              with a re-run of ERA-Land analysis. This script has
#              been used to create the initial conditions i05e.
#
# Date: 7.8.2012
#
# Author: Omar Bellprat (omar.bellprat@ic3.cat)
#
#-------------------------------------------------------------------

indir='/cfu/releases/ic/atmos/T255L91'  # Dir of initical conditions (ic)
landdir='/cfu/releases/ic/atmos/T255L91/g53c_clim'  # Dir of ERA-Land analysis
refic='b0io' # ERA-Interim ic's
newic='i05i' # New atmospheric ic's using land parameters from g53c

smonths=("05" "11") # Start dates (May,Nov)

param="32.128/33.128/39.128/40.128/41.128/42.128/139.128/141.128/170.128/183.128/235.128/236.128/238.128"  # List of parameters from ERA-Land
param=("asn/rsn/swvl1/swvl2/swvl3/swvl4/stl1/sd/stl2/stl3/skt/stl4/tsn") # Short Names of parameters

tmpdir='/scratch/${USER}/tmp_i05i'


if [ ! -d "${tmpdir}" ]; then
  mkdir -p ${tmpdir}
fi

if [ ! -d "${indir}/${newic}" ]; then
  mkdir -p ${indir}/${newic}
fi

cd ${tmpdir}

for i in $(seq 1993 2009) # Time window of ic's
do
    echo 'GRIB copying year' ${i}
    for f in $(seq 0 9)
    do
    echo 'GRIB copying member fc'${f}

        for j in "${smonths[@]}"
        do  
            rm ${tmpdir}/*
            tar -xf ${indir}/${refic}/${refic}_fc${f}_${i}${j}0100.tar.gz -C .
            grib_copy -w shortName!=$param ICMGGXXXXINIT ICMGGXXXXINIT_noland # Copy atmosperhic fields excluding land parameters
            cat ${landdir}/clim_g53c_19930501.grb >> ICMGGXXXXINIT_noland # Concatenate new land parameters to original ic's
            mv ICMGGXXXXINIT_noland ICMGGXXXXINIT
            tar -zcvf ${indir}/${newic}/${newic}_fc${f}_${i}${j}0100.tar.gz ICM*
        done
    done
done
rm -r ${tmpdir}
