#!/bin/bash
#
# ---------------------------------------------------------------------------------------------------------------
# CURRENT SETUP - Runs via cron every 15 minutes to check MESO sectors (hh:00, hh:15, hh:30, hh:45) based
#                 on user entered fields. 
#                 The sector nominal date/time/lat/lon are then compared to NHC ATCF B-deck files
#                 against any active storms and INVESTS.
#                 If MESO sector is matched to an active storm or invest and we have all the necessary data inputs, 
#                 the HIRES clouds and winds are generated for all cloud-track channels (Ch02, Ch07, Ch08, Ch14).
#                 All L1B files and all ATCF b-deck files are pulled from SCDR.
# ----------------------------------------------------------------------------------------------------------------
#
# 
# example:  ./run_HIRES_MESO.bash <sat> <sector> <hires> <jday> <hour> <min>
# 
#           <sat>       -  Satellite to process
#                          '16' for GOES-16 (as GOES-East)
#                          '18' for GOES-18 (as GOES-West)
#                          '19' for GOES-19 (as GOES-East) 
#           <sector>    -  ABI sector to process
#                          'MESO1' for MESO sector 1 
#                          'MESO2' for MESO sector 2 
#           <hires>      - Process HIRES or Nominal resolution winds
#                          '1' Nominal Resolution 
#                          '2' High Resolution (meant to be used only for TC MESO sector processing)
#           <jday>       - Day for image search on SCDR
#                          YYYYDDD  format
#           <hour>       - Hour for image search on SCDR
#                          HH  format
#           <min>        - Minute for image search on SCDR
#                          MM  format (00, 15, 30, 45)
#
# aab 11/14/2024 
#

# Set Library paths, etc.
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/data/smcd/goesr_winds/routine/mcidas/lib:/data/data311/qzhao/gnu_v5_3_1/local/ecCodes/lib:/data/data311/qzhao/gnu_v4_8_5/local/netcdf/lib:/data/data311/qzhao/gnu_v4_8_5/local/hdf5/lib:/data/data311/qzhao/gnu_v4_8_5/local/szip/lib:/lib:/data/starfs1/utils/mcidas-x/2022.1//tcl/lib:/data/starfs1/utils/mcidas-x/2022.1//tcl/lib/tk8.5:/data/starfs1/utils/mcidas-x/2022.1//tcl/lib/tcl8.4:/data/data311/qzhao/gnu_v4_8_5/local/netcdff/lib
export PATH=$PATH:.:/data/smcd/goesr_winds/routine/mcidas/bin:/data/starfs1/bin:/data/home004/abailey/miniconda3/bin:/data/starfs1/utils/mcidas-x/2022.1/bin:/data/starfs1/utils/mcidas-x/2022.1/tcl/bin:/usr/condabin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/opt/puppetlabs/bin


echo ' '
echo "============================================================"
echo "============================================================"
echo "    Start run_HIRES_MESO.bash: "$(date)
echo "============================================================"

# check command line arguments
sat=$1            # possible values: 16, 17, 18, 19
sector=$2         # possible values: MESO1 or MESO2 
hires_job=$3      # possible values: 1 or 2 
jday=$4           # YYYYDDD format
hour=$5           # HH format
min=$6            # MM format (00, 15, 30, 45)

# define working paths
# additional paths are defined later based on basin/storm# if winds are produced. 
McIDAS_data_path=/data/smcd/goesr_winds/routine/mcidas/data/
run_ASF_AMV_Main_PATH=/data/smcd8/abailey/run_ASF_GEO_TC_HIRES_MESO/
amv_out_path=./GOES-${sat}_TC_HIRES/${sector}/
amv_file_list=${amv_out_path}file_list_amv
amv1_file_list=${amv_out_path}file_list_amv1
amv2_file_list=${amv_out_path}file_list_amv2
amv3_file_list=${amv_out_path}file_list_amv3
bdeck_file_working_dir=${run_ASF_AMV_Main_PATH}GOES-${sat}_TC_HIRES/${sector}/b-deck_file_working_dir/

# wind types and channels used to loop over AMV processing
windtype=( ircd wvcd swcd vzcd )
channels=( 14 08 07 02 )

echo ' ' 
echo Switch to framework directory to run: 
echo ${run_ASF_AMV_Main_PATH}
cd ${run_ASF_AMV_Main_PATH}

# Set product string for SCDR commands.
if [ "$sector" = "MESO1" ] || [ "$sector" = "MESO2" ]
then
  product_str="ABI-L1B-RADM"
  sector_str="MESO"

else

  echo "ERROR: HIRES winds are only run for MESO sectors!"
  echo "       User must specify sector MESO1 or MESO2 only."
  echo ' '

  echo Cleanup older log files in working directories...keep around 5 days worth of log files
  echo "${run_ASF_AMV_Main_PATH}clnmax_dir.bash -d 960 ${run_ASF_AMV_Main_PATH}GOES-${sat}_TC_HIRES/${sector}/cron_logs g${sat}_meso${sector:4:1}_hires_rhw"
        ${run_ASF_AMV_Main_PATH}clnmax_dir.bash -d 960 ${run_ASF_AMV_Main_PATH}GOES-${sat}_TC_HIRES/${sector}/cron_logs g${sat}_meso${sector:4:1}_hires_rhw

  exit 1 

fi

#Set calendar day and time variables for MESO sector SCDR search based on user entered values
calday=$(date -d "${jday:0:4}-01-01 ${jday:4:3} days -1 day" '+%Y-%m-%d')
caldaym1=$(date -d "${jday:0:4}-01-01 ${jday:4:3} days -2 day" '+%Y-%m-%d')

# Need to remove leading zero to handle octal (base 8) in conditionals
hour_nozero=$(echo $hour | sed 's/^0*//')

# Set the times for pulling imagery from SCDR
# HiRes MESO winds are scheduled to check every 15-minutes (hh:00, hh:15, hh:30, hh:45) 
# and use 1-min imagery. 
if [[ "$hour_nozero" = "0"  && "$min" = "00" ]]
then
   start_date=$caldaym1
   start_time=23:59
   end_time=${hour}:02
   end_date=$calday
else 
   start_date=$calday
   let hourm1=${hour_nozero}-1
   if (( $hourm1 < 10 ))
   then
      hourm1=$(echo 0$hourm1)
   fi
fi

if [[ "$min" = "00" && "$hour_nozero" > 0 ]]
then
   start_time=${hourm1}:59
   end_time=${hour}:02
   end_date=$calday

elif (( $min == 15 ))
then
   start_time=${hour}:14
   end_time=${hour}:17
   end_date=$calday

elif (( $min == 30 ))
then
   start_time=${hour}:29
   end_time=${hour}:32
   end_date=$calday

elif (( $min == 45 ))
then
   start_time=${hour}:44
   end_time=${hour}:47
   end_date=$calday
fi

echo ' '
echo Checking GOES-$sat $sector L1B data from SCDR for $start_date at $start_time UTC through $end_date at $end_time UTC
echo ' '

echo Query SCDR for list of $sector tracking files. We need at least three.
# The list will contain the record # and the full path to the file.
# example:
#
#1 /data/scdr050/G-16/disk01/AVTiYZM4R8uhNGxXTEoejw/OR_ABI-L1b-RadC-M6C02_G16_s20170722157510_e20170722200282_c20170722200321.nc
#2 /data/scdr050/G-16/disk02/GiklkIIARr2429uesn0XOQ/OR_ABI-L1b-RadC-M6C02_G16_s20170722202510_e20170722205282_c20170722205322.nc
#3 /data/scdr050/G-16/disk01/EpE1033tQ7WY09GCqfgW+w/OR_ABI-L1b-RadC-M6C02_G16_s20170722207510_e20170722210282_c20170722210320.nc
#

if [ "$sector" = "MESO1" ]
then

  echo scdr-files -t $product_str --satid G${sat} --stime "$start_date $start_time" --etime "$end_date $end_time" 
       scdr-files -t $product_str --satid G${sat} --stime "$start_date $start_time" --etime "$end_date $end_time" \
        |grep RadM1 | grep C01 | awk '{d=$0;print NR " " d}' > $amv_file_list
       echo ' '

elif [ "$sector" = "MESO2" ]
then

  echo scdr-files -t $product_str --satid G${sat} --stime "$start_date $start_time" --etime "$end_date $end_time" 
       scdr-files -t $product_str --satid G${sat} --stime "$start_date $start_time" --etime "$end_date $end_time" \
        |grep RadM2 | grep C01 | awk '{d=$0;print NR " " d}' > $amv_file_list
       echo ' '

fi

# save the number of tracking files
num_amv_files=$(wc -l $amv_file_list | awk '{print $1}')

echo "Number of AMV files found: "$num_amv_files
echo ' ' 
# Check the number of available files: 
# If we have at least 3, we can process Cloud Track winds (all Modes). 
# If we have at least 7, we can process Mode-6 Full Disk CSWV winds.
# If we have at least 13, we can process Mode-6 CONUS CSWV winds. 
# NOTE: Script currently only handles Mode-6 CSWV Full Disk and CONUS processing. 
#       Modifications required for other CSWV Modes/sectors. 
#
# Search on the record number to assign the variables. Long file names with the full path
# are used when copying the data and the short names are used on the GEOCAT command line.
#

  # If more than 3 files are available use the most recent 3 images.
  if (( $num_amv_files == 3 ))
  then
    # assign records 1, 2, and 3 to variables

    file1=$(awk '/^1 /{a=$2;print a}' $amv_file_list)
    file2=$(awk '/^2 /{a=$2;print a}' $amv_file_list)
    file3=$(awk '/^3 /{a=$2;print a}' $amv_file_list)
    file1_short=$(awk -F/ '/^1 /{print $NF}' $amv_file_list)
    file2_short=$(awk -F/ '/^2 /{print $NF}' $amv_file_list)
    file3_short=$(awk -F/ '/^3 /{print $NF}' $amv_file_list)

  elif (( $num_amv_files == 4 ))
  then
    # assign records 2, 3, and 4 to variables

    file1=$(awk '/^2 /{a=$2;print a}' $amv_file_list)
    file2=$(awk '/^3 /{a=$2;print a}' $amv_file_list)
    file3=$(awk '/^4 /{a=$2;print a}' $amv_file_list)
    file1_short=$(awk -F/ '/^2 /{print $NF}' $amv_file_list)
    file2_short=$(awk -F/ '/^3 /{print $NF}' $amv_file_list)
    file3_short=$(awk -F/ '/^4 /{print $NF}' $amv_file_list)

  elif (( $num_amv_files == 5 ))
  then
    # assign records 3, 4, and 5 to variables

    file1=$(awk '/^3 /{a=$2;print a}' $amv_file_list)
    file2=$(awk '/^4 /{a=$2;print a}' $amv_file_list)
    file3=$(awk '/^5 /{a=$2;print a}' $amv_file_list)
    file1_short=$(awk -F/ '/^3 /{print $NF}' $amv_file_list)
    file2_short=$(awk -F/ '/^4 /{print $NF}' $amv_file_list)
    file3_short=$(awk -F/ '/^5 /{print $NF}' $amv_file_list)

  elif (( $num_amv_files == 6 ))
  then
    # assign records 4, 5, and 6 to variables

    file1=$(awk '/^4 /{a=$2;print a}' $amv_file_list)
    file2=$(awk '/^5 /{a=$2;print a}' $amv_file_list)
    file3=$(awk '/^6 /{a=$2;print a}' $amv_file_list)
    file1_short=$(awk -F/ '/^4 /{print $NF}' $amv_file_list)
    file2_short=$(awk -F/ '/^5 /{print $NF}' $amv_file_list)
    file3_short=$(awk -F/ '/^6 /{print $NF}' $amv_file_list)

  elif (( $num_amv_files == 7 ))
  then
    # assign records 5, 6, and 7 to variables

    file1=$(awk '/^5 /{a=$2;print a}' $amv_file_list)
    file2=$(awk '/^6 /{a=$2;print a}' $amv_file_list)
    file3=$(awk '/^7 /{a=$2;print a}' $amv_file_list)
    file1_short=$(awk -F/ '/^5 /{print $NF}' $amv_file_list)
    file2_short=$(awk -F/ '/^6 /{print $NF}' $amv_file_list)
    file3_short=$(awk -F/ '/^7 /{print $NF}' $amv_file_list)

  else
    echo ' ' 
    echo "ERROR: We do not have 3 images for processing!"
    echo Exiting...
    echo "=================================================================="

    echo Cleanup older log files in working directories...keep around 5 days worth of log files
    echo "${run_ASF_AMV_Main_PATH}clnmax_dir.bash -d 960 ${run_ASF_AMV_Main_PATH}GOES-${sat}_TC_HIRES/${sector}/cron_logs g${sat}_meso${sector:4:1}_hires_rhw"
          ${run_ASF_AMV_Main_PATH}clnmax_dir.bash -d 960 ${run_ASF_AMV_Main_PATH}GOES-${sat}_TC_HIRES/${sector}/cron_logs g${sat}_meso${sector:4:1}_hires_rhw

    exit 1
  fi

echo "Continue with the following images from SCDR:"
echo "file1: " $file1
echo "file2: " $file2
echo "file3: " $file3
echo "file1_short: " $file1_short
echo "file2_short: " $file2_short
echo "file3_short: " $file3_short
echo ' '

# strip image times (start of scan) from the file names
image_time1=$(echo $file1_short | awk -F_ '{print $4}')
image_time2=$(echo $file2_short | awk -F_ '{print $4}')
image_time3=$(echo $file3_short | awk -F_ '{print $4}')

# strip Julian date from file names
# the yyyyddd string starts at position 1 and has length 7
#
# position: 012345678
#            yyyyddd
# example:  s20170722157510
jdate1=${image_time1:1:7}
jdate2=${image_time2:1:7}
jdate3=${image_time3:1:7}

# now strip hhmmss string from file names
# the hhmmss string starts at position 8 and has length 6
#
# position: 012345678
#                   hhmmss
# example:  s20170722157510
hhmmss1=${image_time1:8:6}
hhmmss2=${image_time2:8:6}
hhmmss3=${image_time3:8:6}

echo 'Image Triplet Day and Time to be processed:'
echo $jdate1 $hhmmss1
echo $jdate2 $hhmmss2
echo $jdate3 $hhmmss3
echo ' '

#
# export middle image date/time for tagging logs
export Middle_Image_Time="${jdate2}_${hhmmss2}"

echo ' '
echo 'Pull central Lat/Lon of all MESO images in the triplet and check that'
echo "they are consistent across all images (i.e., the sector hasn't moved)."
echo 'The target (middle) image Lat/Lon will be used to compare'
echo 'to any active TCs for possible HIRES processing:'
meso_img1_lat_center=$(ncdump -h $file1 | grep geospatial_lat_center | awk -F= '{print $2}' | cut -c 1-6 | awk '{$1=$1;print}')
meso_img1_lon_center=$(ncdump -h $file1 | grep geospatial_lon_center | awk -F= '{print $2}' | cut -c 1-7 | awk '{$1=$1;print}')
meso_img2_lat_center=$(ncdump -h $file2 | grep geospatial_lat_center | awk -F= '{print $2}' | cut -c 1-6 | awk '{$1=$1;print}')
meso_img2_lon_center=$(ncdump -h $file2 | grep geospatial_lon_center | awk -F= '{print $2}' | cut -c 1-7 | awk '{$1=$1;print}')
meso_img3_lat_center=$(ncdump -h $file3 | grep geospatial_lat_center | awk -F= '{print $2}' | cut -c 1-6 | awk '{$1=$1;print}')
meso_img3_lon_center=$(ncdump -h $file3 | grep geospatial_lon_center | awk -F= '{print $2}' | cut -c 1-7 | awk '{$1=$1;print}')

# Not sure why, but when the MESO sector Lon has a *.0 value, that field is sometimes filled with an 'f' in the L1B files. 
# Reset it for later position checks.  
mlon_check1=$(echo $meso_img1_lon_center | awk -F "." '{print $1}')
mlon_check2=$(echo $meso_img1_lon_center | awk -F "." '{print $2}')
mlon_check3=$(echo $meso_img2_lon_center | awk -F "." '{print $1}')
mlon_check4=$(echo $meso_img2_lon_center | awk -F "." '{print $2}')
mlon_check5=$(echo $meso_img3_lon_center | awk -F "." '{print $1}')
mlon_check6=$(echo $meso_img3_lon_center | awk -F "." '{print $2}')

if [ "$mlon_check2" = "f" ]; then
   meso_img1_lon_center=${mlon_check1}.0
fi
if [ "$mlon_check4" = "f" ]; then
   meso_img2_lon_center=${mlon_check3}.0
fi
if [ "$mlon_check6" = "f" ];then
   meso_img3_lon_center=${mlon_check5}.0
fi

echo GOES-$sat $sector triplet Lat/Lon:
echo meso_img1_lat_center=$meso_img1_lat_center
echo meso_img1_lon_center=$meso_img1_lon_center
echo meso_img2_lat_center=$meso_img2_lat_center
echo meso_img2_lon_center=$meso_img2_lon_center
echo meso_img3_lat_center=$meso_img3_lat_center
echo meso_img3_lon_center=$meso_img3_lon_center
echo ' '

if  [[ "${meso_img1_lat_center}" = "${meso_img2_lat_center}"  &&  "${meso_img1_lat_center}" = "${meso_img3_lat_center}" ]] \
    && [[ "${meso_img1_lon_center}" = "${meso_img2_lon_center}"  &&  "${meso_img1_lon_center}" = "${meso_img3_lon_center}" ]]
then
   echo ' '
   echo Images in the triplet have a consistent Lat/Lon...continue processing...
   echo ' '
else
   echo ' ' 
   echo "=================================================================="
   echo "ERROR: We do not have consistent Lat/Lon for processing this image triplet."
   echo "ERROR: The $sector sector was repositioned."
   echo "       Exiting..."
   echo "=================================================================="
   echo ' '

   echo Cleanup older log files in working directories...keep around 5 days worth of log files
   echo "${run_ASF_AMV_Main_PATH}clnmax_dir.bash -d 960 ${run_ASF_AMV_Main_PATH}GOES-${sat}_TC_HIRES/${sector}/cron_logs g${sat}_meso${sector:4:1}_hires_rhw"
         ${run_ASF_AMV_Main_PATH}clnmax_dir.bash -d 960 ${run_ASF_AMV_Main_PATH}GOES-${sat}_TC_HIRES/${sector}/cron_logs g${sat}_meso${sector:4:1}_hires_rhw

   exit 1
fi

echo Query SCDR for list of files needed by the cloud algorithms for the middle image time.
echo We need 16 files.

echo scdr-files -t $product_str --satid G${sat} --stime "$start_date $start_time" --etime "$end_date $end_time" 
     scdr-files -t $product_str --satid G${sat} --stime "$start_date $start_time" --etime "$end_date $end_time" | \
     grep $image_time1 | awk '/C01|C02|C03|C04|C05|C06|C07|C08|C09|C10|C11|C12|C13|C14|C15|C16/\
                                                {d=$0;print d}' > $amv1_file_list
     scdr-files -t $product_str --satid G${sat} --stime "$start_date $start_time" --etime "$end_date $end_time" | \
     grep $image_time2 | awk '/C01|C02|C03|C04|C05|C06|C07|C08|C09|C10|C11|C12|C13|C14|C15|C16/\
                                                {d=$0;print d}' > $amv2_file_list
     scdr-files -t $product_str --satid G${sat} --stime "$start_date $start_time" --etime "$end_date $end_time" | \
     grep $image_time3 | awk '/C01|C02|C03|C04|C05|C06|C07|C08|C09|C10|C11|C12|C13|C14|C15|C16/\
                                                {d=$0;print d}' > $amv3_file_list
     echo ' '

num_cloud_files=$(wc -l $amv2_file_list | awk '{print $1}')

echo "Number of Cloud Files: "$num_cloud_files
echo ' '

#
# If we have all of the necessary files for winds, check ATCF b-deck files for any lat/lon 
# storm matches...otherwise exit.
#
if (( $num_cloud_files == 16 ))
then
  echo We have enough bands to run cloud algorithms. 
  echo Continue processing with check of NHC ATCF b-deck files against 
  echo $sector sector Lat/Lon for geolocation match with any current storms.

else
  echo "ERROR: We do not have enough bands for cloud algorithms."
  echo Exiting...
  echo "=================================================================="

  echo Cleanup older log files in working directories...keep around 5 days worth of log files
  echo "${run_ASF_AMV_Main_PATH}clnmax_dir.bash -d 960 ${run_ASF_AMV_Main_PATH}GOES-${sat}_TC_HIRES/${sector}/cron_logs g${sat}_meso${sector:4:1}_hires_rhw"
        ${run_ASF_AMV_Main_PATH}clnmax_dir.bash -d 960 ${run_ASF_AMV_Main_PATH}GOES-${sat}_TC_HIRES/${sector}/cron_logs g${sat}_meso${sector:4:1}_hires_rhw

  exit 1
fi 

echo ' ' 
echo "============================================================================="
echo "Create ATCF bdeck file lists for checking storms and invests against $sector sector."
echo "${run_ASF_AMV_Main_PATH}run_Make_Basin_Storm_Files.bash $sat $sector"
      ${run_ASF_AMV_Main_PATH}run_Make_Basin_Storm_Files.bash $sat $sector

# Cycle through any active storms and invests listed in files created from above script.  
# Separate bdeck file listings are created for each basin depending on the satellite 
# being processed. The files are staged to their respective working directories: 

if [[ "$sat" = "16" || "$sat" = "19" ]]
then
   echo '==========================================================================='
   bdeck_filecheck=$(ls -l ${bdeck_file_working_dir}ATL_bdeckfile_list_current | awk -F " " '{print $5}')

   if [ "$bdeck_filecheck" = "0" ]
   then
      #echo "Currently no active storms in Atlantic Basin."
      run_atl_basin=no

   else
      # Cycle through any active storms or invests listed in files created from above script.  
      filename_albasin=${bdeck_file_working_dir}AL_Basin_current_storms_list
      while read fbasin; do
         echo ' '
         bdeck_file_latest_SCDR_ATL=$fbasin
         echo bdeck_file_latest_SCDR_ATL: $bdeck_file_latest_SCDR_ATL

         Basin_atl=$(tail -1 ${bdeck_file_latest_SCDR_ATL}  | awk -F "," '{print $1}')
         StormNum_atl=$(tail -1 ${bdeck_file_latest_SCDR_ATL}  | awk -F "," '{print $2}')
         yyyymmddhh_atl=$(tail -1 ${bdeck_file_latest_SCDR_ATL}  | awk -F "," '{print $3}')
         StormLat_atl=$(tail -1 ${bdeck_file_latest_SCDR_ATL}  | awk -F "," '{print $7}')
         StormLon_atl=$(tail -1 ${bdeck_file_latest_SCDR_ATL}  | awk -F "," '{print $8}')
         StormName_atl=$(tail -1 ${bdeck_file_latest_SCDR_ATL}  | awk -F "," '{print $28}')

         echo ' '
         echo "Checking $sector sector against $Basin_atl basin for $yyyymmddhh_atl "
         echo "Storm Number: $StormNum_atl "
         echo "Storm Name: $StormName_atl "
         echo "Storm Position Lat/Lon: ${StormLat_atl}/${StormLon_atl}"
         echo ' '

         # Convert to numerical Lat/Lon values
         SLat=$(${run_ASF_AMV_Main_PATH}run_Convert_LatLon.bash ${StormLat_atl} ${StormLon_atl} | awk -F " " '{print $1*0.1}')
         SLon=$(${run_ASF_AMV_Main_PATH}run_Convert_LatLon.bash ${StormLat_atl} ${StormLon_atl} | awk -F " " '{print $2*0.1}')

         echo ' '
         echo "Check if Lat/Lons are within +/-5 degrees..."
         echo "Center point Lat/Lon for current $sector sector for GOES-${sat}: "
         MLat=$meso_img2_lat_center
         MLon=$meso_img2_lon_center
         echo MLat, MLon= $MLat $MLon
         echo ' '
         echo "Center point Lat/Lon for current ATL storm being checked: "
         echo SLat, SLon= $SLat $SLon

         MESOlatdiff="$(echo "$MLat - $SLat" | bc)"
         MESOlondiff="$(echo "$MLon - $SLon" | bc)"
         echo ' '
         echo MESOlatdiff: ${MESOlatdiff#-} MESOlondiff: ${MESOlondiff#-}

         MLAT_Diff=${MESOlatdiff#-}
         MLON_Diff=${MESOlondiff#-}

         # Need this to compare real numbers...there's likely a better way to do this in bash that I don't know about.
         MLat_compare=$(echo "$MLAT_Diff <= 5" | bc)
         MLon_compare=$(echo "$MLON_Diff <= 5" | bc)

         if [[ "$MLat_compare" -eq 1 && "$MLon_compare" -eq 1 ]]
         then
            echo ' '
            echo '==================================================== '
            echo ATL storm and current $sector sector are geolocated!
            echo '==================================================== '
            run_atl_basin=yes
            Basin=AL_Basin
            StormNumber=$(echo $StormNum_atl | awk '{$1=$1;print}')
            StormName=$(echo $StormName_atl | awk '{$1=$1;print}')
            Storm_yyyymmddhh=$yyyymmddhh_atl
            bdeck_file_latest_SCDR=$bdeck_file_latest_SCDR_ATL
	    break_loop=1
         else
	    break_loop=0
         fi
        
	 if [ "$break_loop" -eq "1" ]
         then
             break
	 else
            run_atl_basin=no
         fi

      done < "$filename_albasin"

      if [ "$run_atl_basin" = "no" ]
      then
         echo ' '
         echo '==================================================== '
         echo ATL storm and $sector sector are not geolocated.
         echo No ATL basin HiRes winds for this $sector cycle.
         echo Check EPAC basin...
         echo '==================================================== '
      fi

   fi #bdeck filecheck

   if [ "$run_atl_basin" = "no" ]
   then
      #echo " "
      #echo "======================================================="
      #echo Check EPAC Basin files for possible match to $sector sector
      bdeck_filecheck=$(ls -l ${bdeck_file_working_dir}EPAC_bdeckfile_list_current | awk -F " " '{print $5}')

      if [ "$bdeck_filecheck" = "0" ]
      then
         #echo ' '
         #echo "Currently no active storms or invests in East Pacific Basin."
         #echo "============================================================"
         run_epac_basin=no

      else
         # Cycle through any active storms listed in files created from above script.
         filename_epbasin=${bdeck_file_working_dir}EP_Basin_current_storms_list
         while read fbasin; do
            echo ' '
            bdeck_file_latest_SCDR_EPAC=$fbasin
            echo bdeck_file_latest_SCDR_EPAC: $bdeck_file_latest_SCDR_EPAC
            echo ' '

            Basin_epac=$(tail -1 ${bdeck_file_latest_SCDR_EPAC}  | awk -F "," '{print $1}')
            StormNum_epac=$(tail -1 ${bdeck_file_latest_SCDR_EPAC}  | awk -F "," '{print $2}')
            yyyymmddhh_epac=$(tail -1 ${bdeck_file_latest_SCDR_EPAC}  | awk -F "," '{print $3}')
            StormLat_epac=$(tail -1 ${bdeck_file_latest_SCDR_EPAC}  | awk -F "," '{print $7}')
            StormLon_epac=$(tail -1 ${bdeck_file_latest_SCDR_EPAC}  | awk -F "," '{print $8}')
            StormName_epac=$(tail -1 ${bdeck_file_latest_SCDR_EPAC}  | awk -F "," '{print $28}')
   
            echo ' '
            echo "Checking $sector sector against $Basin_epac basin for $yyyymmddhh_epac "
            echo "Storm Number: $StormNum_epac "
            echo "Storm Name: $StormName_epac "
            echo "Storm Position Lat/Lon: ${StormLat_epac}/${StormLon_epac}"
            echo ' '

            # Convert to numerical Lat/Lon values
            SLat=$(${run_ASF_AMV_Main_PATH}run_Convert_LatLon.bash ${StormLat_epac} ${StormLon_epac} | awk -F " " '{print $1*0.1}')
            SLon=$(${run_ASF_AMV_Main_PATH}run_Convert_LatLon.bash ${StormLat_epac} ${StormLon_epac} | awk -F " " '{print $2*0.1}')

            echo "Check if Lat/Lons are within +/-5 degrees..."
            echo "Center point Lat/Lon for current $sector sector for GOES-${sat}: "
            echo MLat, MLon= $MLat $MLon
            echo ' '
            echo "Center point Lat/Lon for current storm being checked: "
            echo SLat, SLon= $SLat $SLon

            MESOlatdiff="$(echo "$MLat - $SLat" | bc)"
            MESOlondiff="$(echo "$MLon - $SLon" | bc)"
            echo ' '
            echo MESOlatdiff: ${MESOlatdiff#-} MESOlondiff: ${MESOlondiff#-}

            MLAT_Diff=${MESOlatdiff#-}
            MLON_Diff=${MESOlondiff#-}

            # Need this to compare real numbers...
            MLat_compare=$(echo "$MLAT_Diff <= 5" | bc)
            MLon_compare=$(echo "$MLON_Diff <= 5" | bc)

            if [[ "$MLat_compare" -eq 1 && "$MLon_compare" -eq 1 ]]
            then
               echo ' '
               echo '===================================================== '
               echo EPAC Storm and current $sector sector are geolocated!
               echo '===================================================== '
               run_epac_basin=yes
               Basin=EP_Basin
               StormNumber=$(echo $StormNum_epac | awk '{$1=$1;print}')
	       StormName=$(echo $StormName_epac | awk '{$1=$1;print}')
               Storm_yyyymmddhh=$yyyymmddhh_epac
               bdeck_file_latest_SCDR=$bdeck_file_latest_SCDR_EPAC
               break_loop=1
            else
               break_loop=0
            fi

            if [ "$break_loop" -eq "1" ]
            then
               break
            else
               run_epac_basin=no
            fi

         done < "$filename_epbasin"

         if [ "$run_epac_basin" = "no" ]
         then
            echo ' '
            echo '===================================================== '
            echo Storm and $sector sector are not geolocated.
            echo No EPAC basin HiRes winds for this $sector cycle.
            echo '===================================================== '
         fi
      fi # bdeck file check
   fi # epac basin check

   if [[ "$run_atl_basin" = "no" && "$run_epac_basin" = "no" ]]
   then
      # No winds to make for this cycle.
      echo ' '
      echo Exiting processing...
      echo ' '
      echo Cleanup older log files in working directories...keep around 5 days worth of log files
      echo "${run_ASF_AMV_Main_PATH}clnmax_dir.bash -d 960 ${run_ASF_AMV_Main_PATH}GOES-${sat}_TC_HIRES/${sector}/cron_logs g${sat}_meso${sector:4:1}_hires_rhw"
            ${run_ASF_AMV_Main_PATH}clnmax_dir.bash -d 960 ${run_ASF_AMV_Main_PATH}GOES-${sat}_TC_HIRES/${sector}/cron_logs g${sat}_meso${sector:4:1}_hires_rhw

      exit 1
   else
      echo ' '
      echo "================================================================================"
      echo "We have everything we need for processing HIRES MESO winds and a Lat/Lon"
      echo "match to a current TC or INVEST being tracked. Setup the processing environment for"
      echo "HIRES TC winds (or use existing environment if storm is already being tracked)."
      echo "================================================================================"
      echo ' '
   fi

elif [ "$sat" = "18" ]
then
   echo ' '
   echo '==========================================================================='
   bdeck_filecheck=$(ls -l ${bdeck_file_working_dir}EPAC_bdeckfile_list_current | awk -F " " '{print $5}')

   if [ "$bdeck_filecheck" = "0" ]
   then
      #echo ' '
      #echo "Currently no active storms in East Pacific Basin."
      echo "=================================================="
      run_epac_basin=no

   else
      # Cycle through any active storms listed in files created from above script.
      filename_epbasin=${bdeck_file_working_dir}EP_Basin_current_storms_list
      while read fbasin; do
         echo ' '
         echo '========================'
         echo ' '
         bdeck_file_latest_SCDR_EPAC=$fbasin
         echo bdeck_file_latest_SCDR_EPAC: $bdeck_file_latest_SCDR_EPAC

         Basin_epac=$(tail -1 ${bdeck_file_latest_SCDR_EPAC}  | awk -F "," '{print $1}')
         StormNum_epac=$(tail -1 ${bdeck_file_latest_SCDR_EPAC}  | awk -F "," '{print $2}')
         yyyymmddhh_epac=$(tail -1 ${bdeck_file_latest_SCDR_EPAC}  | awk -F "," '{print $3}')
         StormLat_epac=$(tail -1 ${bdeck_file_latest_SCDR_EPAC}  | awk -F "," '{print $7}')
         StormLon_epac=$(tail -1 ${bdeck_file_latest_SCDR_EPAC}  | awk -F "," '{print $8}')
         StormName_epac=$(tail -1 ${bdeck_file_latest_SCDR_EPAC}  | awk -F "," '{print $28}')

         echo ' '
         echo "Checking $sector sector against $Basin_epac basin for $yyyymmddhh_epac "
         echo "Storm Number: $StormNum_epac "
         echo "Storm Name: $StormName_epac "
         echo "Storm Position Lat/Lon: ${StormLat_epac}/${StormLon_epac}"
         echo ' '

         # Convert to numerical Lat/Lon values
         SLat=$(${run_ASF_AMV_Main_PATH}run_Convert_LatLon.bash ${StormLat_epac} ${StormLon_epac} | awk -F " " '{print $1*0.1}')
         SLon=$(${run_ASF_AMV_Main_PATH}run_Convert_LatLon.bash ${StormLat_epac} ${StormLon_epac} | awk -F " " '{print $2*0.1}')

         echo ' '
         echo "Check if Lat/Lons are within +/-5 degrees..."
         echo "Center point Lat/Lon for current $sector sector for GOES-${sat}: "
         MLat=$meso_img2_lat_center
         MLon=$meso_img2_lon_center
         echo MLat, MLon= $MLat $MLon
         echo ' '
         echo "Center point Lat/Lon for current EPAC storm being checked: "
         echo SLat, SLon= $SLat $SLon

         MESOlatdiff="$(echo "$MLat - $SLat" | bc)"
         MESOlondiff="$(echo "$MLon - $SLon" | bc)"
         echo ' '
         echo MESOlatdiff: ${MESOlatdiff#-} MESOlondiff: ${MESOlondiff#-}

         MLAT_Diff=${MESOlatdiff#-}
         MLON_Diff=${MESOlondiff#-}

         # Need this to compare real numbers...there's likely a better way to do this in bash that I don't know about.
         MLat_compare=$(echo "$MLAT_Diff <= 5" | bc)
         MLon_compare=$(echo "$MLON_Diff <= 5" | bc)

         if [[ "$MLat_compare" -eq 1 && "$MLon_compare" -eq 1 ]]
         then
            echo ' '
            echo '==================================================== '
            echo EPAC storm and current $sector sector are geolocated!
            echo '==================================================== '
            run_epac_basin=yes
            Basin=EP_Basin
            StormNumber=$(echo $StormNum_epac | awk '{$1=$1;print}')
            StormName=$(echo $StormName_epac | awk '{$1=$1;print}')
            Storm_yyyymmddhh=$yyyymmddhh_epac
            bdeck_file_latest_SCDR=$bdeck_file_latest_SCDR_EPAC
            break_loop=1
         else
            break_loop=0
	 fi

         if [ "$break_loop" -eq "1" ]
         then
            break
         else
            run_epac_basin=no
         fi

      done < "$filename_epbasin"

      if [ "$run_epac_basin" = "no" ]
      then
         echo ' '
         echo '==================================================== '
         echo EPAC storm and $sector sector are not geolocated.
         echo No EPAC basin HiRes winds for this $sector cycle.
         echo Check CPAC basin...
         echo '==================================================== '
      fi
   fi # bdeck filecheck

   if [ "$run_epac_basin" = "no" ]
   then
      #echo Check CPAC Basin files for possible match to $sector sector
       bdeck_filecheck=$(ls -l ${bdeck_file_working_dir}CPAC_bdeckfile_list_current | awk -F " " '{print $5}')

      if [ "$bdeck_filecheck" = "0" ]
      then
         #echo ' '
         #echo "Currently no active storms in Central Pacific Basin."
         run_cpac_basin=no

      else

         # Cycle through any active storms listed in files created from above script.
         filename_cpbasin=${bdeck_file_working_dir}CP_Basin_current_storms_list
         while read fbasin; do
            echo ' '
            bdeck_file_latest_SCDR_CPAC=$fbasin
            echo bdeck_file_latest_SCDR_CPAC: $bdeck_file_latest_SCDR_CPAC
            echo ' '

            Basin_cpac=$(tail -1 ${bdeck_file_latest_SCDR_CPAC}  | awk -F "," '{print $1}')
            StormNum_cpac=$(tail -1 ${bdeck_file_latest_SCDR_CPAC}  | awk -F "," '{print $2}')
            yyyymmddhh_cpac=$(tail -1 ${bdeck_file_latest_SCDR_CPAC}  | awk -F "," '{print $3}')
            StormLat_cpac=$(tail -1 ${bdeck_file_latest_SCDR_CPAC}  | awk -F "," '{print $7}')
            StormLon_cpac=$(tail -1 ${bdeck_file_latest_SCDR_CPAC}  | awk -F "," '{print $8}')
            StormName_cpac=$(tail -1 ${bdeck_file_latest_SCDR_CPAC}  | awk -F "," '{print $28}')

            echo ' '
            echo "Checking $sector sector against $Basin_cpac basin for $yyyymmddhh_cpac "
            echo "Storm Number: $StormNum_cpac "
            echo "Storm Name: $StormName_cpac "
            echo "Storm Position Lat/Lon: ${StormLat_cpac}/${StormLon_cpac}"
            echo ' '

            # Convert to numerical Lat/Lon values
            SLat=$(${run_ASF_AMV_Main_PATH}run_Convert_LatLon.bash ${StormLat_cpac} ${StormLon_cpac} | awk -F " " '{print $1*0.1}')
            SLon=$(${run_ASF_AMV_Main_PATH}run_Convert_LatLon.bash ${StormLat_cpac} ${StormLon_cpac} | awk -F " " '{print $2*0.1}')

            echo "Check if Lat/Lons are within +/-5 degrees..."
            echo "Center point Lat/Lon for current $sector sector for GOES-${sat}: "
            echo MLat, MLon= $MLat $MLon
            echo ' '
            echo "Center point Lat/Lon for current storm being checked: "
            echo SLat, SLon= $SLat $SLon

            MESOlatdiff="$(echo "$MLat - $SLat" | bc)"
            MESOlondiff="$(echo "$MLon - $SLon" | bc)"
            echo ' '
            echo MESOlatdiff: ${MESOlatdiff#-} MESOlondiff: ${MESOlondiff#-}

            MLAT_Diff=${MESOlatdiff#-}
            MLON_Diff=${MESOlondiff#-}

            # Need this to compare real numbers...
            MLat_compare=$(echo "$MLAT_Diff <= 5" | bc)
            MLon_compare=$(echo "$MLON_Diff <= 5" | bc)

            if [[ "$MLat_compare" -eq 1 && "$MLon_compare" -eq 1 ]]
            then
               echo ' '
               echo '===================================================== '
               echo CPAC Storm and current $sector sector are geolocated!
               echo '===================================================== '
               run_cpac_basin=yes
               Basin=CP_Basin
               StormNumber=$(echo $StormNum_cpac | awk '{$1=$1;print}')
	       StormName=$(echo $StormName_cpac | awk '{$1=$1;print}')
	       Storm_yyyymmddhh=$yyyymmddhh_cpac
               bdeck_file_latest_SCDR=$bdeck_file_latest_SCDR_CPAC
	       break_loop=1
            else
	       break_loop=0
            fi

            if [ "$break_loop" -eq "1" ]
            then
               break
            else
               run_cpac_basin=no
            fi

	 done < "$filename_cpbasin"

         if [ "$run_cpac_basin" = "no" ]
         then
            echo ' '
	    echo '===================================================== '
            echo Storm and $sector sector are not geolocated.
            echo No CPAC basin HiRes winds for this $sector cycle.
            echo '===================================================== '
         fi
      fi # bdeck file check
   fi # end cpac basin check

   if [[ "$run_epac_basin" = "no" && "$run_cpac_basin" = "no" ]]
   then
      # No winds to make for this cycle.
      echo ' '
      echo Exiting processing...
      echo ' '
      echo Cleanup older log files in working directories...keep around 5 days worth of log files
      echo "${run_ASF_AMV_Main_PATH}clnmax_dir.bash -d 960 ${run_ASF_AMV_Main_PATH}GOES-${sat}_TC_HIRES/${sector}/cron_logs g${sat}_meso${sector:4:1}_hires_rhw"
            ${run_ASF_AMV_Main_PATH}clnmax_dir.bash -d 960 ${run_ASF_AMV_Main_PATH}GOES-${sat}_TC_HIRES/${sector}/cron_logs g${sat}_meso${sector:4:1}_hires_rhw

      exit 1
   else
      echo ' '
      echo "================================================================================"
      echo "We have everything we need for processing HIRES MESO winds and a Lat/Lon"
      echo "match to a current TC or INVEST being tracked. Setup the processing environment for"
      echo "HIRES TC winds (or use existing environment if storm is already being tracked)."
      echo "================================================================================"
      echo ' '
   fi

fi #end sat conditional check

echo ' '
echo Check to see if we have already made winds for this storm/invest and sector. If not, create
echo and setup processing environment for HiRes MESO winds.
echo ' '

echo "ls ${run_ASF_AMV_Main_PATH}GOES-${sat}_TC_HIRES/${sector}/${Basin}/${jdate2:0:4}/$StormNumber"
      ls ${run_ASF_AMV_Main_PATH}GOES-${sat}_TC_HIRES/${sector}/${Basin}/${jdate2:0:4}/$StormNumber
command=$?      

if [ $command -ne 0 ]; then
   echo ' '
   echo This is a new storm for $sector sector and the processing of HiRes winds. Setup the processing environment... 
   ${run_ASF_AMV_Main_PATH}run_Env_Setup_Hires_Process.bash ${sat} ${sector} ${Basin} ${jdate2:0:4} $StormNumber  

   # Write new Storm info to master list of storms for the year...used to keep track of processing
   # Master list has one entry for each new storm when it's first tracked by MESO area.
   echo $Basin $StormNumber $StormName ${jdate2:0:4} GOES-$sat $sector >> ${bdeck_file_working_dir}${Basin}_bdeck_master_storm_list

else
   echo ' '
   echo Processing environment already exists for this storm for $sector sector.   
   echo Run this set of HiRes winds.  

fi

# Set processing directories for winds based on Sat/Sector/Basin/Year/StormNumber: 
HIRES_Winds_Process_Path=${run_ASF_AMV_Main_PATH}GOES-${sat}_TC_HIRES/${sector}/${Basin}/${jdate2:0:4}/${StormNumber}/
ABI_Intermediate_Data_PATH=${HIRES_Winds_Process_Path}Intermediate_Data_HIRES_${sector}/
ABI_L1B_PATH=${ABI_Intermediate_Data_PATH}L1B/
bdeck_file_working_dir=${HIRES_Winds_Process_Path}b-deck_files/

amv_out_path=./GOES-${sat}_TC_HIRES/${sector}/

echo ' '
echo  Make sure L1B space is cleaned out...
echo "rm ${ABI_L1B_PATH}*.nc"
      rm ${ABI_L1B_PATH}*.nc
echo ' '

echo Copy L1B files from SCDR to working files directory.
cp $(awk '{a=$1;print a}' $amv1_file_list) $ABI_L1B_PATH
cp $(awk '{a=$1;print a}' $amv2_file_list) $ABI_L1B_PATH
cp $(awk '{a=$1;print a}' $amv3_file_list) $ABI_L1B_PATH

#Set L1B input file names for cloud and amv scripts
  l1b_input1=$ABI_L1B_PATH$file1_short
  l1b_input2=$ABI_L1B_PATH$file2_short
  l1b_input3=$ABI_L1B_PATH$file3_short

# Used for testing - see what we want to process...
process="Both"
#process="Cloud"
#process="AMV"

if [ "$process" = "Cloud" ] || [ "$process" = "Both" ]
then
  echo ' '
  echo '==============================='
  echo ' '
  echo "Run Cloud Algorithms for GOES-$sat $sector, generate gfs files:"
  echo "${run_ASF_AMV_Main_PATH}run_GOES_CLOUDS_HIRES.bash $sat $sector $ABI_Intermediate_Data_PATH $l1b_input2"
        ${run_ASF_AMV_Main_PATH}run_GOES_CLOUDS_HIRES.bash $sat $sector $ABI_Intermediate_Data_PATH $l1b_input2

  echo ' '
  echo '==============================='
  echo ' '
fi

if [ "$process" = "AMV" ] || [ "$process" = "Both" ]
then

  # Loop over all cloud-track windtypes/channels...
  for (( j = 0 ; j < 4 ; j++ ))
    do
    AMV_Band=${channels[$j]}
    WindType=${windtype[$j]}
    echo ' '
    echo '==============================='
    echo ' '
    echo Generate Cloud-Track AMVs for Ch$AMV_Band...Wind Type $WindType:
    echo "For all is vanity and a striving after wind...(with a tip 'o the hat to windco!)"
    echo ' '
    echo "${run_ASF_AMV_Main_PATH}run_GOES_WINDS_HIRES.bash $sat $sector $AMV_Band $hires_job $HIRES_Winds_Process_Path $WindType $l1b_input1 $l1b_input2 $l1b_input3"
          ${run_ASF_AMV_Main_PATH}run_GOES_WINDS_HIRES.bash $sat $sector $AMV_Band $hires_job $HIRES_Winds_Process_Path $WindType $l1b_input1 $l1b_input2 $l1b_input3

    echo ' '
    echo '==============================='
    echo ' '

    echo ' '
    echo "Convert ASCII AMV file to McIDAS MD and save to rotating archive"
    echo "Copy ASCII file to McIDAS /data"

    rm ${McIDAS_data_path}M${sector:4:1}ascii

    echo ' '
     echo "cp ${HIRES_Winds_Process_Path}${WindType}/ASCII_AMV.GOES${sat}.${jdate2}.${hhmmss2:0:4}.CH_${AMV_Band}.* ${McIDAS_data_path}M${sector:4:1}ascii"
           cp ${HIRES_Winds_Process_Path}${WindType}/ASCII_AMV.GOES${sat}.${jdate2}.${hhmmss2:0:4}.CH_${AMV_Band}.* ${McIDAS_data_path}M${sector:4:1}ascii

    # Switch to mcidas /data dir
    cd $McIDAS_data_path

    # Set McIDAS MD file #
    if [ "$sat" = "16" ]
    then
      MD_file=7130
    elif [ "$sat" = "18" ]
    then
      MD_file=7131
    elif [ "$sat" = "19" ]
    then
      MD_file=7132
    fi

    mdu.k DEL $MD_file
    mdu.k MAKE $MD_file WIEX 35

    echo " "
    echo "txt2mdx.k M${sector:4:1}ascii $MD_file WIEX NLON=1"
          txt2mdx.k M${sector:4:1}ascii $MD_file WIEX NLON=1

    # switch back to framework directory
    cd ${run_ASF_AMV_Main_PATH}

    echo ' '
    echo "Copy MD file back to rotating archive in local product directory"
    echo "cp ${McIDAS_data_path}MDXX$MD_file ${HIRES_Winds_Process_Path}${WindType}/MDXX_G${sat}.${jdate2}.${hhmmss2:0:4}.C${AMV_Band}.${sector}"
          cp ${McIDAS_data_path}MDXX$MD_file ${HIRES_Winds_Process_Path}${WindType}/MDXX_G${sat}.${jdate2}.${hhmmss2:0:4}.C${AMV_Band}.${sector}


# Used for testing... 
    create_bufr=Yes
    #create_bufr=No

    # Check to see if we want to generate BUFR files
    if [ "$create_bufr" = "Yes" ]
    then
      echo ' '
      echo "Generate BUFR files..."
      echo ' '

      # set PCF inputs
      BUFR_Input_File_nc=$(ls ${HIRES_Winds_Process_Path}${WindType}/GOES${sat}_ABI_*_${sector:0:4}_${jdate2}_${hhmmss2:0:4}_*_WINDS_AMV_EN-*.nc)
      BUFR_TABLE=/data/home004/abailey/git-assisst_fw/BUFR/run_NB/WINDS_NB_BUFR_Table
      OPS_BIN=/data/home004/abailey/git-assisst_fw/BUFR/code/main
      CWORDSH=/data/data311/qzhao/gnu/DAP5/SOURCE/cwordsh/cwordsh.x

      # Create PCF for new template BUFR perl script
      echo 'PROD_TYPE=NB-EN-WINDS'           >  ${HIRES_Winds_Process_Path}${WindType}/bufr/G${sat}ent_${WindType}_NPR.pl.PCF
      echo 'CONVERSION=NC2BUFR'              >> ${HIRES_Winds_Process_Path}${WindType}/bufr/G${sat}ent_${WindType}_NPR.pl.PCF
      echo 'NPR_INPUT='${BUFR_Input_File_nc} >> ${HIRES_Winds_Process_Path}${WindType}/bufr/G${sat}ent_${WindType}_NPR.pl.PCF
      echo 'BUFR_TABLE='${BUFR_TABLE}        >> ${HIRES_Winds_Process_Path}${WindType}/bufr/G${sat}ent_${WindType}_NPR.pl.PCF
      echo 'OPS_BIN='${OPS_BIN}              >> ${HIRES_Winds_Process_Path}${WindType}/bufr/G${sat}ent_${WindType}_NPR.pl.PCF
      echo 'CWORDSH='${CWORDSH}              >> ${HIRES_Winds_Process_Path}${WindType}/bufr/G${sat}ent_${WindType}_NPR.pl.PCF

      # cd to product bufr sub-directory
      cd ${HIRES_Winds_Process_Path}${WindType}/bufr

      echo link PCF for new template BUFR...
      echo "ln -sf G${sat}ent_${WindType}_NPR.pl.PCF NPR.pl.PCF"
            ln -sf G${sat}ent_${WindType}_NPR.pl.PCF NPR.pl.PCF

      echo Run perl script for new template BUFR file...
      echo perl NPR.pl
           perl NPR.pl

      # Switch back to main processing framework directory  
      cd ${run_ASF_AMV_Main_PATH}

    fi # Done with BUFR

  done # windtype loop
fi # AMV processing

# If we generated winds, do some housekeeping and cleanup.
if [[ "$run_atl_basin" = "yes" || "$run_epac_basin" = "yes" || "$run_cpac_basin" = "yes" ]]
then
   echo ' '
   echo "We generated winds with this cycle. Do some housekeeping and cleanup..."

   # Put a copy of current bdeck file used in processing in storm specific working directory for reference
   cp $bdeck_file_latest_SCDR $bdeck_file_working_dir

   # Used for testing... 
   #cloud_files=Keep
   cloud_files=Delete
   if [ "$cloud_files" = "Delete" ]
   then
     echo ' '
     echo "Deleting Cloud files from ${ABI_Intermediate_Data_PATH}..."
     echo "rm ${ABI_Intermediate_Data_PATH}GOES${sat}_ABI_*_${sector:0:4}_${jdate2}_${hhmmss2:0:4}_*.nc"
           rm ${ABI_Intermediate_Data_PATH}GOES${sat}_ABI_*_${sector:0:4}_${jdate2}_${hhmmss2:0:4}_*.nc

   else
     echo "Keeping Cloud files from this run in ${ABI_Intermediate_Data_PATH}..."
     echo ' '
   fi
fi

echo ' '
echo "Move the cron log files from the GOES-$sat $sector working directory to the storm-specific directory"
echo "cp ${run_ASF_AMV_Main_PATH}GOES-${sat}_TC_HIRES/${sector}/cron_logs/g16_meso1_hires_rhw1256_${calday}_${hour}${min}.* ${HIRES_Winds_Process_Path}cron_logs"
      cp ${run_ASF_AMV_Main_PATH}GOES-${sat}_TC_HIRES/${sector}/cron_logs/g16_meso1_hires_rhw1256_${calday}_${hour}${min}.* ${HIRES_Winds_Process_Path}cron_logs


echo Cleanup older log files in working directories...keep around 5 days worth of log files
echo "${run_ASF_AMV_Main_PATH}clnmax_dir.bash -d 960 ${run_ASF_AMV_Main_PATH}GOES-${sat}_TC_HIRES/${sector}/cron_logs g${sat}_meso${sector:4:1}_hires_rhw"
      ${run_ASF_AMV_Main_PATH}clnmax_dir.bash -d 960 ${run_ASF_AMV_Main_PATH}GOES-${sat}_TC_HIRES/${sector}/cron_logs g${sat}_meso${sector:4:1}_hires_rhw

echo ' '
echo "Check /dev/shm in case any jobs that were killed prematurely left behind old files/directories..."
echo "rm -rf /dev/shm/AMV_*_framework_job*"
      rm -rf /dev/shm/AMV_*_framework_job*
echo "rm -rf /dev/shm/CLOUD_*_framework_job*"
      rm -rf /dev/shm/CLOUD_*_framework_job*

echo ' '
echo ' '
echo "=================================================================="
echo "   end processing time: "$(date)
echo "=================================================================="
echo "=================================================================="

