#!/bin/sh
#  ------------------------------------------------------------------------
#  This script generates BUFR messages corresponding to a given user DX
#  (BUFR dictionary) table.  It then appends these messages to every
#  tankfile in the given BUFR database whose type corresponds to the
#  given table, unless the tankfile subtype is explicitly excluded via
#  the environment variable $APXDX_EXCLUDE.  If this environment variable
#  is unset, then all tankfiles of the specified type are appended.
#
#  For example, if $APXDX_EXCLUDE=xx002,xx030 and the given BUFR database is
#  /dcom/us007003 and the given DX table is /nwprod/fix/bufrtab.255, then the
#  script will generate BUFR messages from /nwprod/fix/bufrtab.255 and append
#  them to every tankfile located within every b255 subdirectory of the
#  /dcom/us007003 database *except* for any xx002 or xx030 tankfiles.
#
#  NOTE: The script is set up to run in the Bourne shell. If you are a
#  C-shell user, enter 'sh ./run_apxdx.sh'.
#  ------------------------------------------------------------------------
#  Usage: run_apxdx.sh <BUFRdbroot> <DXtable>
#
#  where:
#  <BUFRdbroot>  [path/]filename of BUFR database root directory
#  <DXtable>     [path/]filename of DX dictionary table
#
#  optional environment variable:
#  $APXDX_EXCLUDE   comma-separated list of tankfile subtypes to exclude
#  ------------------------------------------------------------------------

[ $# -ne 2 ] && { echo; echo "Usage: $0 <BUFRdbroot> <DXtable>";
                  echo;
                  echo "where:";
                  echo "  <BUFRdbroot> = [path/]filename of BUFR database root";
                  echo "  <DXtable>    = [path/]filename of DX table";
                  echo; exit 99; }

utilush=${utilush:-/nwprod/util/ush}

excludes=${APXDX_EXCLUDE:-xx999}

BUFRdbroot=${1}

DXtable=${2}

#  Generate a list of all of the subdirectories corresponding to this table.

dirname=b`basename ${DXtable} | cut -f2 -d.`

dirs="`ls -1d ${BUFRdbroot}/20*/${dirname}`"

for dir in ${dirs}
do

    cd ${dir}

#   Generate a list of all of the tankfiles in this subdirectory, then append
#   the updated table to each one that has not been explicitly excluded.

    tanks="`ls -1 xx*`"

    for tank in ${tanks}
    do
	if [ `echo "${excludes}" | egrep -c ${tank}` -eq 0 ]
        then 
	    echo "Using ${utilush}/apxdx to append ${DXtable} messages to ${dir}/${tank}"
 	    ${utilush}/apxdx ${dir}/${tank} ${DXtable}
        fi
    done

done
