#!/bin/sh
#
#  UTILITY SCRIPT NAME :  meteomrf.sh
#               AUTHOR :  Hua-Lu Pan
#         DATE WRITTEN :  02/03/97
#
#  Abstract:  This utility script produces BUFR file of
#             station forecasts from the GFS and the MRF suites.
#
#     Input:  none
#
echo "History: February 1997 - First implementation of this utility script"
echo "History: January  1999 - First implementation on IBM SP"
#

set -x

if test "$F00FLAG" = "YES"
then
   f00flag=".true."
else
   f00flag=".false."
fi

export pgm=meteoflx
. prep_step

cat << EOF > metflxparm
 &NAMKEN
  nout=$FINT,lonf=$LONB,latg=$LATB,nsfc=80,
  nstart=$FSTART,nend=$FEND,nint=$FINT,f00=$f00flag,
/
EOF
#
# Truncate to JCAP and LEVS
#
hh=$FSTART
while  test $hh -le $FEND
do  
   ln -sf $COMIN/${RUN}.${cycle}.sfluxgrbf${hh} flxf${hh} 
   hh=` expr $hh + $FINT `
   if test $hh -lt 10
   then
      hh=0$hh
   fi
done

export XLFUNIT_8="$PARMbufr/bufr_stalist.meteo.mrf"
export XLFUNIT_81="gfs12.dat"
export XLFUNIT_82="metflxmrf"

startmsg
$EXECbufr/bufr_meteoflx < metflxparm >> $pgmout 2>errfile
export err=$?;err_chk

rm flxf*

export pgm=meteomrf
. prep_step

if test "$MAKEBUFR" = "YES"
then
   bufrflag=".true."
else
   bufrflag=".false."
fi

cat << EOF > meteoparm
 &NAMMET
  iromb=0,maxwv=$JCAP,levs=$LEVS,makebufr=$bufrflag,
  nstart=$FSTART,nend=$FEND,nint=$FINT,nsfc=80,f00=$f00flag,
/
EOF

POE_OPTS=${POE_OPTS:-"-pgmmodel mpmd -ilevel 3 -labelio yes \
     -stdoutmode ordered"}

rm -rf $DATA/poescript

hh=$FSTART
while  test $hh -le $FEND
do  
   SIGLEVS=$(echo levs|/nwprod/exec/global_sighdr $COMIN/${RUN}.${cycle}.sf${hh})
   if test $SIGLEVS -eq $LEVS
   then
      ln -sf $COMIN/${RUN}.${cycle}.sf${hh} sigf${hh} 
   else
      export SIGINP=$COMIN/${RUN}.${cycle}.sf${hh}
      export SFCINP=$COMIN/${RUN}.${cycle}.bf${hh}
      export SIGOUT=$DATA/sigf${hh}
      export SFCOUT=$DATA/sfcf${hh}
      if [[ $NET = gfs ]]
      then
         pgm_chs=/nwprod/util/ush/chgres_mpi.sh
         POE=YES
         mkdir -p -m 775 $DATA/$hh
         echo "$pgm_chs $SIGINP $SFCINP $SIGOUT $SFCOUT $DATA/$hh" >>$DATA/poescript
      else
         /nwprod/ush/global_chgres.sh
      fi
   fi

   hh=` expr $hh + $FINT `
   if test $hh -lt 10
   then
      hh=0$hh
   fi
done  

chmod 775 $DATA/poescript
export MP_PGMMODEL=mpmd
export MP_CMDFILE=$DATA/poescript

# Use Multi-Processing to change resolution:
if test "$POE" = "YES"
then
     /usr/bin/poe -cmdfile $DATA/poescript $POE_OPTS
     export err=$?; err_chk
fi

#  define input BUFR table file.
export XLFUNIT_1="$PARMbufr/bufr_${NET}_class1.tbl"
export XLFUNIT_8="$PARMbufr/bufr_stalist.meteo.mrf"
export XLFUNIT_12="metflxmrf"
#  define output BUFR file for meteogram profiles.
export XLFUNIT_90="$OUTFILE"
export XLFUNIT_91="met1.dat"

startmsg
$EXECbufr/bufr_meteomrf < meteoparm >> $pgmout 2>errfile
export err=$?;err_chk

rm  sigf* metflxmrf gfs12.dat
