#!/usr/bin/bash

# subarea - arkimet postprocess to crop a GRIB file
#
# Copyright (C) 2013  ARPA-SIM <urpsim@smr.arpa.emr.it>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Author: Emanuele Di Giacomo <edigiacomo@arpa.emr.it>

function print_usage()
{
	printf "Usage $0 MINLON MINLAT MAXLON MAXLAT\n"
}

# called without arki-xargs (arki-query --postproc=subarea)
if [ x"$ARKI_XARGS_FORMAT" == x ]
then
	# Controllo che i parametri siano esattamente 4
	[[ $# -eq 4 ]] || { print_usage >&2 ; exit 1 ; }
        exec arki-xargs --max-size=1M -- $0 $@
fi

subareafile=$(mktemp)
cleanup()
{
	rm -f $subareafile
}
trap cleanup EXIT

params="-a $1 -b $2 -c $3 -d $4 $5"
LOG4C_APPENDER=stderr LOG4C_PRIORITY=ERROR \
vg6d_transform \
	--trans-mode=s \
	--trans-type=zoom \
	--sub-type=coord \
	--ilon=$1 --ilat=$2 --flon=$3 --flat=$4 \
	-- $5 $subareafile && cat $subareafile
