#!/bin/ksh
# example script for retrieving fire emission flux densities produced by MACC D-FIRE from MARS
# to be executed on ecgate.ecmwf.int
# 20100225 j.kaiser@ecmwf.int
# 20100316 j.kaiser@ecmwf.int add option to write ASCII files

set -ex

### user setup ###

ExpID=f7i2
# see http://www.gmes-atmosphere.eu/about/project_structure/input_data/d_fire/ProductsInMARS/

FirstDay=20100223
Last_Day=20100224
#        YYYYMMDD

# Hourly emission flux densities are stored in the middle of the period for which they are valid:
# (artificial diurnal cycle, only available in selected ExpID.)
# Time='0030/to/2330/by/0100'

# Daily emission flux densitiess are also stored in the middle of the period for which they are valid:
Time=1200

# Monthly emission flux denisities are stored as daily values, which are constant for all days of each month.
# So, you get the full information by retrieving any single day of each month.

ParamID='80.210/102.210'
# see http://www.ecmwf.int/services/archive/d/parameters/order=grib_parameter/table=210/

Domain='global'
# or boundaries in deg N and deg E: 'N/W/S/E', e.g. '75/-25/30/75' for Europe
# To avoid automatic interpolation use only for 0.1 deg fields and specify multiples of 0.1 deg. 

OutDir=$SCRATCH
# You must have loads of space in the output directory. $SCRATCH is suitable on ecgate.
OutGribFile=FireEmissions.grb
# The file will be gzipped.

#OutAsciiArchive=FireEmissions.tar
# If you uncomment the line above ASCII representations of all fields are produced.
# The tar archive contains the gzipped ASCII fields, each in a separate file.
# The three columns in the ASCII files list the latitude [deg], longitude [deg]
# and flux densitie [kg/s/m2] of all grid points.


### modify below at your own risk ##
# !!! In particlar, you must avoid interpolation by MARS or EMOSLIB. !!!

cd $OutDir

mars <<EOF
  retrieve,
    class=rd,
    type=fc,
    stream=da,
    levtype=sfc,
    time=$Time,
    step=00,
    expver=$ExpID,
    date=$FirstDay/to/$Last_Day,
    param=$ParamID,
    area=$Domain,
    target="$OutGribFile"
EOF

if [ ! "$OutAsciiArchive" = "" ]
then
  use grib_api
  mkdir -p tmpRetrieveFireEmissions
  cd tmpRetrieveFireEmissions
  rm -f *
  grib_copy ../$OutGribFile '[date]_[param].grb'
  for fgrb in $(ls *.grb)
  do
    grib_get_data $fgrb | gzip -c1 > $(echo $fgrb | sed 's/\.grb/.dat.gz/')
  done
  tar cvf ../$OutAsciiArchive *.dat.gz 
  cd ..
fi

gzip -v1f $OutGribFile
pwd
ls -l $OutGribFile.gz $OutAsciiArchive

