#!/bin/bash
#
# Script that takes data from an ICMCL file 
# and replaces the dataDate key with another year
#

# load modules (on glogin.hlrn.de)
module load intel eccodes cdo

# the ICMCL with data from any year
icmcl=$2 

# org_year - year in the original data that we want to replace
# set_year - year we want to set instead
org_year=2000
set_year=$1

# loop over all days in year
curryear=$set_year
currmon=01
currday=01
currdate=$(date -d "${curryear}-${currmon}-${currday}T00:00:00" "+%Y-%m-%dT%H:%M:%S")
while [ $curryear == $set_year ]
do  
    
    # set dataDate strings
    set_dataDate=$(printf "%4d%02d%02d" ${curryear} ${currmon} ${currday} )
    org_dataDate=$(printf "%4d%02d%02d" ${org_year} ${currmon} ${currday} )    
    
    echo " set dataDate to ${set_dataDate}"
    # cut this day from the ICMCL file
    grib_copy -w dataDate=${org_dataDate} ${icmcl} tmp_${set_dataDate}.grb
    # replace dataDate
    grib_set -s dataDate=${set_dataDate} -w dataDate=${org_dataDate} tmp_${set_dataDate}.grb ICMCL_${set_dataDate}
    rm -f tmp_${set_dataDate}.grb
    
    # step one day forward
    currdate=$(date -d "$currdate 1 day" "+%Y-%m-%dT%H:%M:%S")    
    curryear=$(date -d "$currdate" "+%Y")
    currmon=$(date -d "$currdate" "+%m")
    currday=$(date -d "$currdate" "+%d")
    currmon=${currmon#0}
    currday=${currday#0}
done

# glue to one file
grib_copy ICMCL_${set_year}???? ICMCL_${set_year}
rm -f ICMCL_${set_year}????


