#!/bin/bash
#
# This script first creates a HAR file (bioagg.har) which holds the mapping
# information to aggregate data to the 19 regions used by GTAP-BIO, then it
# aggregates the carbon data from the parent directory to these 19 regions, 
# creating the file carbon19.har.
#
# Temporary files are removed when the program using them exits without error,
# but left in place for inspection in case of error.
#
# Author:  Rich Plevin (plevin@ucdavis.edu)
# Created: 16 SEP 2013

AGGMAP=bioagg		# Basename of aggregation map and related files

MAPTXT=$AGGMAP.txt
MAPHAR=$AGGMAP.har
MAPSTI=$AGGMAP.sti
MAPLOG=$AGGMAP.log

echo "Generating $MAPSTI"
rm -f $MAPLOG $MAPSTI

# Generate an STI file to build the mapping HAR file
echo 'bat'			>  $MAPSTI
echo ''				>> $MAPSTI
echo 'n'			>> $MAPSTI
echo 'bioagg.har'		>> $MAPSTI
echo 'at'			>> $MAPSTI
echo 'bioagg.txt'		>> $MAPSTI
echo 'A'			>> $MAPSTI
echo 'at'			>> $MAPSTI
echo '../country/csets.txt'	>> $MAPSTI
echo 'A'			>> $MAPSTI
echo 'ex'			>> $MAPSTI
echo '0'			>> $MAPSTI

rm -f $MAPLOG

echo "Generating $MAPHAR"
modhar -sti $MAPSTI -los $MAPLOG

# Remove the generated STI file and log if modhar succeeded.
if [ $? == 0 ]; then
    rm -f $MAPLOG $MAPSTI
else
    echo "Modhar failed with error $?"
    exit
fi

# The following files are referenced below
DDATA=../carbon134.har		# C stocks for 134 GTAP regions
DSETS=../v87set.har		# GTAP 8 set definitions
ASETS=bioagg.har		# maps to 19 regions for GTAP-BIO
ADATA=carbon19.har		# C stocks aggregated to desired regions

# Temporary files created
LOGFILE=aggcarbon.log
STIFILE=aggcarbon.sti

# Order of files defined in aggcarbon.tab:
#   Input files:
#     DDATA = disaggregate data
#     DSETS = set specification for disaggregate data
#     ASETS = set specification for aggregate data
#   Output files:
#     ADATA = aggregated data in GTAP notation

echo "Generating $STIFILE"

echo 'bat  !  This runs the program in "batch" mode'     > $STIFILE
echo ''							>> $STIFILE 
echo $DDATA						>> $STIFILE
echo $DSETS						>> $STIFILE
echo $ASETS						>> $STIFILE
echo $ADATA						>> $STIFILE

rm -f $LOGFILE
echo "Aggregating carbon data $DDATA to $ADATA"

../aggcarbon -sti $STIFILE -los $LOGFILE

# Remove STI file and log if aggcarbon succeeds
if [ $? == 0 ]; then
    echo SKIPPING rm -f $STIFILE $LOGFILE
else
    echo "aggcarbon exited with error $?"
    exit 1
fi

echo "Done"
