#!/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 i05j.
#
# Date: 7.8.2012
#
# Author: Omar Bellprat (omar.bellprat@ic3.cat)
#
#-------------------------------------------------------------------

indir='/cfu/releases/ic/atmos/T511L91' # Dir of initical conditions (ic)
landdir='/cfu/releases/ic/atmos/T511L91/g53m_clim' # Dir of ERA-Land analysis
refic='b0it' # ERA-Interim ic's
newic='i05j' # 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/obellprat/tmp_i05j'

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_g53m_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}
