#!/bin/bash
#

#
# We require a certain nomenclature for the daily files to be processed :
# ModelName_Period_Sampling_Variable.nc :
# ModelName : Name of the model or institution which produced the file.
# Period : 19890101_20131231 in our case as this is the period of the forcing.
# Sampling : 1D as daily output have been requested.
# Variable : The name of the variable in the file.
#
#

#
# Rename and correct received files
#
EXP="WFDE5_CRU_GPCC"
e="wfd"
cd ${EXP}
for f in $(ls *_${e}_*.nc) ; do
    nf=$(echo $f | sed -e "s/${e}/${EXP}/")
    echo "Move $f to $nf"
    mv $f $nf
done
if [ -e mv RadTMax_${EXP}_8914.nc ] ; then
    mv RadTMax_${EXP}_8914.nc  RadTmax_${EXP}_8914.nc
fi
cd ..

EXP="ETHZ_Avg"
e="ethz"
cd ${EXP}
for f in $(ls *_${e}_*.nc) ; do
    nf=$(echo $f | sed -e "s/_${e}_/_${EXP}_/")
    echo "Move $f to $nf"
    mv $f $nf
done
if [ -e RadTMax_${EXP}_8914.nc ] ; then 
    mv RadTMax_${EXP}_8914.nc  RadTmax_${EXP}_8914.nc
fi
cd ..

EXP="IPSL_Avg"
e="iavg"
cd ${EXP}
for f in $(ls *_${e}_*.nc) ; do
    nf=$(echo $f | sed -e "s/_${e}_/_${EXP}_/")
    echo "Move $f to $nf"
    mv $f $nf
done
if [ -e RadTMax_${EXP}_8914.nc ] ; then
    mv RadTMax_${EXP}_8914.nc  RadTmax_${EXP}_8914.nc
fi
cd ..

EXP="IPSL_Alt"
e="ialt"
cd ${EXP}
for f in $(ls *_${e}_*.nc) ; do
    nf=$(echo $f | sed -e "s/_${e}_/_${EXP}_/")
    echo "Move $f to $nf"
    mv $f $nf
done
if [ -e RadTMax_${EXP}_8914.nc ] ; then
    mv RadTMax_${EXP}_8914.nc  RadTmax_${EXP}_8914.nc
fi
cd ..

VAR="ECanop PotEvap Qsb Rainf Snowf ESoil Qh RadTmax SWE SoilWet Evap Qle RadT SWnet SubSnow LWnet Qs RadTmin SnowDepth TVeg"

EXP="ETHZ_Avg IPSL_Avg IPSL_Alt"

for e in ${EXP} ; do
    echo "==> Experiment ${e}"
    if [ ! -d  ../MeteoCat/${e} ] ; then
	mkdir ../MeteoCat/${e}
	mkdir ../MeteoCat/${e}/TS_DA
	for v in ${VAR} ; do
	    echo "=====>> $e $v <<====="
	    ncdump -h ${e}/${v}_${e}_8914.nc | grep UNLIM
	    cp ${e}/${v}_${e}_8914.nc ../MeteoCat/${e}/TS_DA/MeteoCat_${e}_19890101_20140101_1D_${v}.nc
	done
    fi
done

EXP="WFDE5_CRU_GPCC"
for e in ${EXP} ; do
    echo "==> Experiment ${e}"
    if [ ! -d  ../MeteoCat/${e} ] ; then
	mkdir ../MeteoCat/${e}
	mkdir ../MeteoCat/${e}/TS_DA
	for v in ${VAR} ; do
	    echo "=====>> $e $v <<====="
	    ncdump -h ${e}/${v}_${e}_8914.nc | grep UNLIM
	    ncrename -v lon,LON -v lat,LAT ${e}/${v}_${e}_8914.nc \
		    ../MeteoCat/${e}/TS_DA/MeteoCat_${e}_19890101_20140101_1D_${v}.nc
	done
    fi
done
