#!/bin/bash
# SFCCOPY - copy the surface analysis file specified in -b to the file
# specified in -B, changing the date to be that given in -d (default 0).
# The forecast hour is set to 0.0 to indicate a new initial condition to
# the MRF.
# Example:
# sfccopy -b from -B to -d 2000101112 copies the file "from" to the file "to"
#   unchanged, except that "to" has its date field set to Oct. 11, 2000, 12Z,
#   and the forecast hour is 0.
#
# Requires Eric's programs sub, bfp and scale to rewrite the binary header of
# the input file.
#
# On Karman, the input and output files must be big-endian, which requires
# byte-swapping on logical units 1 and 2.  The following environment variable
# is specific to Lahey Fortran.

export FORT90L="-Wl,-T1,-T2"
date=0

while getopts b:B:d: opt
do
    case $opt in
    b)  sfcin=$OPTARG;;
    B)  sfcout=$OPTARG;;
    d)  date=$OPTARG;;
    \?) echo "$0: unknown option" 1>&2; usage; exit 1;;
    esac
done
#
#  The date format used in our scripts is yyyymmddhh, but the date format
#  expected by the MRF is hh mm dd yyyy.  Omit leading 0's from mm and dd.
mrfdate=$(echo $date |\
   awk '{print substr($1,9,2),substr($1,5,2)+0,substr($1,7,2)+0,substr($1,1,4)}')

#  Copy first record and the byte count of the second record to the output.
nbytes=$(bfp I. $sfcin)
if [ "$nbytes" != 32 ]
then
   echo $0: wrong number of bytes in first record of $sfcin 1>&2
   exit 1
fi

#  The record count (=32) includes two 4-byte integer record marks
#  for a total of 40 bytes in the first record.  In addition, we'll copy
#  the input record mark for the second record for a total of 44 bytes.
sub 44b $sfcin > $sfcout

# The forecast hour is 0.0, reflecting the new initial condition to the MRF.
echo 0.0 | scale -aF >> $sfcout 

# Modify the date field to reflect $date.
echo $mrfdate | scale -aI >> $sfcout

# Copy the rest of the surface analysis file
sub -44b-5i $sfcin >> $sfcout
errcode=$?

exit $errcode
