#! /bin/ksh

# This function loops over the specified files, trying to byteswap
# each one.  It assumes that if ssrc returns exit status 0 and
# produces a file of the same size as the input, that byteswapping
# succeeded.  Otherwise, it assumes that the file should not be
# byteswapped.  This is done for each file, so this script can
# handle some files being byteswapped, and some files not being
# byteswapped.

if [[ "$PARAFLAG" == NO ]] ; then
    # Not needed in operations since everything is big endian.
    exit 0
fi

set -x

in=INFILE.UNSWAPPED
out=OUTFILE.SWAPPED

for file in $* ; do
    if [[ ! -e "$file" ]] ; then
        # If the file doesn't exist, skip it.  This prevents
        # creation of zero-sized files when a non-existant file
        # is specified.
        continue
    fi

    /bin/rm -f $in $out
    /bin/ln -s "$file" $in
    
    if ( ! $EXEChwrf/hwrf_ssrc < $in > $out ) ; then
        # SSRC failed, so assume the file should not be
        # byteswapped.
        continue
    fi
    
    if ( ! perl -e "exit ( ( ( -s $in ) == ( -s $out ) ) ? 0 : 1 )" ) ; then
        # In and out files are not exactly the same size, so
        # assume the file should not be byteswapped.
        continue
    fi 

    # If we get here, the file was byteswapped.
    /bin/rm -f "$file"
    /bin/mv -f "$out" "$file"
done

rm -f "$in" "$out"
