#!/bin/bash
# Wrapper script to download, convert, and merge the GFED-4 source data.
# by Christoph Keller, March 2015.

# Download hdf5-files from source:
GetHdf5=0

# Convert hdf5 files to netCDF (using Prasad's IDL script):
Hdf5toNcdf=0

# Merge netCDF files into single files:
NcdfMerge=1

# Download all hdf5 files
if [ $GetHdf5 == 1 ];  then
   ./get_gfed4.sh
fi

# Convert hdf5 files to netCDF 
if [ $Hdf5toNcdf == 1 ]; then

  echo "creating netCDF files from hdf5..."
   
idl << idlenv
gfed4
idlenv

  echo "done!"

fi

# Merge netCDF files into one file
if [ $NcdfMerge == 1 ]; then

  echo "merging netCDF files..."

  # GFED-categories
  CATEGORY=("AGRI" "BORF" "DEFO" "SAVA" "PEAT" "TEMP" "TOTL")

  # loop over all years
  for iyr in {1997..2014}; do

    # eventually create output directory
    if [ ! -d $iyr ]; then
       mkdir $iyr
    fi

    # loop over all months
    for imon in {1..12}; do
      mm=`printf "%02d\n" $imon`

      # define ncdf output file for this date 
      ifile="${iyr}/GFED4_gen.025x025.${iyr}${mm}.nc"

      # verbose
      echo "trying to create file ${ifile}..."

      # loop over all categories
      for icat in ${CATEGORY[@]}; do

        # get this category and file name
        #INFILE="./ncdf/GFED4_DM_${icat}_${iyr}${mm}.generic.025x025.nc"
        INFILE="/as/scratch/ckeller/tmp/GFED4_DM_${icat}_${iyr}${mm}.generic.025x025.nc"

        # merge files into one
        if [ -f $INFILE ]; then
          if [ -f tmp.nc ]; then
            cdo -s merge $INFILE tmp.nc tmp2.nc
            mv tmp2.nc tmp.nc
          else
            cp $INFILE tmp.nc
          fi
        fi
      done #icat

      # this is now the monthly file
      if [ -f tmp.nc ]; then
        nccopy -d1 tmp.nc $ifile
      fi

      # cleanup
      rm -rf tmp.nc

      # eventually also move dailyfrac files
      dfile="/as/scratch/ckeller/tmp/GFED4_dailyfrac_gen.025x025.${iyr}${mm}.nc"
      if [ -f $dfile ]; then
        nccopy -d1 $dfile $iyr/$dfile
      fi

      dfile="/as/scratch/ckeller/tmp/GFED4_3hrfrac_gen.025x025.${iyr}${mm}.nc"
      if [ -f $dfile ]; then
        nccopy -d1 $dfile $iyr/$dfile
      fi
 
    done #imon
  done # iyr
fi

# All done! 
exit 0

