:
#                                            4/95 Wesley Ebisuzaki
# takes a number of grib time series and make synoptic order file
#  (grads compatible)
# 
# grads wants:
# loop by time
#   loop by variable
#     loop by pressure
#       read/write data
#     end loop
#   end loop
# end loop
#
# needs POSIX sort command
# needs wgrib
# TMPDIR = directory for tmp files
# two versions (increasing/decreasing) levels
#
# v1.1 fix bug .. 10m was between 20 mb and 10 mb
#                 new sorting pattern
# v1.2 fix bug introduced by v1.1
#
WGRIB=/wd5/wd51/wd51we/bin/wgrib
tmp=$TMPDIR/junk.$$
tmp=/tmp/junk.$LOGNAME..$$
set -u

if [ $# -lt 2 ] ; then
   echo "v1.2 takes grib time series -> synoptic order file"
   echo "usage: $0 (timeseries wild-card) (output file) (rev)"
   echo "wild card must be in quotes!"
   echo "use rev for theta coordinates"
   exit 8
fi
rev=${3:-NO}

cat `ls $1` >$tmp

if [ $rev = rev ] ; then
  $WGRIB $tmp | sed 's/kpds7=//' | sort -t: -k3,3 -k4,4 -k6,6 -k7n,7 | \
	$WGRIB -i -s -grib $tmp -o $2
else
  $WGRIB $tmp | sed 's/kpds7=//' | sort -t: -k3,3 -k4,4 -k6,6 -k7rn,7 | \
	$WGRIB -i -s -grib $tmp -o $2
fi

rm $tmp
exit 0
