#!/bin/csh
#
set grid = $1
set diag = $2
set area = $3
set metwx = /uufs/chpc.utah.edu/common/home/horel-group/archive
set cgrid = `echo $grid | tr "[a-z]" "[A-Z]" | cut -c1-3`
#
#  Get current date in UTC
#
set yr = ` date -u +%y `
set mn = ` date -u +%m `
set dy = ` date -u +%d `
set hr = ` date -u +%H `
#
#  Get most likely time to be available
#
if ( $4 == "" ) then
  set yr = ` date -u +%y `
  set mn = ` date -u +%m `
  set dy = ` date -u +%d `
  set hr = ` date -u +%H `
  if ( $hr >= 18 ) then
    set hr = 18
  else if ( $hr >= 12 ) then
    set hr = 12
  else if ( $hr >= 6 ) then
    set hr = 06
  else
    set hr = 00
  endif
else
  set yr = `echo $4 | cut -c1-2`
  set mn = `echo $4 | cut -c3-4`
  set dy = `echo $4 | cut -c5-6`
  set hr = `echo $4 | cut -c7-8`
endif
#
#  Is this time available?  If not, try the previous
#
TRYAGAIN:
if ( ! -e $metwx/20$yr$mn$dy/images/models/$grid/$cgrid${diag}_${area}20$yr$mn$dy${hr}F000.gif ) then
   if ( $hr == 18 ) then
      set hr = 12
   else if ( $hr == 12 ) then
      set hr = 06
   else if ( $hr == 06 ) then 
      set hr = 00
   else
      set hr = 18
      set olddate = $yr$mn$dy
      set dy = `/uufs/chpc.utah.edu/sys/bin/datepnum 20$olddate -1 | cut -c5-6`
      set mn = `/uufs/chpc.utah.edu/sys/bin/datepnum 20$olddate -1 | cut -c3-4`
      set yr = `/uufs/chpc.utah.edu/sys/bin/datepnum 20$olddate -1 | cut -c1-2`
      goto TRYAGAIN
   endif
endif
echo looping 20$yr$mn$dy$hr $grid $diag $area
#
# Get previous five days 
#
set todaym1 = `/uufs/chpc.utah.edu/sys/bin/datepnum 20$yr$mn$dy -1`
set todaym2 = `/uufs/chpc.utah.edu/sys/bin/datepnum 20$yr$mn$dy -2` 
set todaym3 = `/uufs/chpc.utah.edu/sys/bin/datepnum 20$yr$mn$dy -3`
set todaym4 = `/uufs/chpc.utah.edu/sys/bin/datepnum 20$yr$mn$dy -4`
set todaym5 = `/uufs/chpc.utah.edu/sys/bin/datepnum 20$yr$mn$dy -5`
#
# Loop it
#
cd $metwx
if ( $grid == gfs004 ) then
/uufs/chpc.utah.edu/sys/bin/qiv -e -s -d 0.1 20$todaym5/images/models/$grid/$cgrid${diag}_${area}*F000.gif 20$todaym4/images/models/$grid/$cgrid${diag}_${area}*F000.gif 20$todaym3/images/models/$grid/$cgrid${diag}_${area}*F000.gif 20$todaym2/images/models/$grid/$cgrid${diag}_${area}*F000.gif 20$todaym1/images/models/$grid/$cgrid${diag}_${area}*F000.gif 20$yr$mn$dy/images/models/$grid/$cgrid${diag}_${area}*F000.gif 20$yr$mn$dy/images/models/$grid/$cgrid${diag}_${area}20$yr$mn$dy${hr}F00[3-6].gif 
else
/uufs/chpc.utah.edu/sys/bin/qiv -e -s -d 0.1 20$todaym5/images/models/$grid/$cgrid${diag}_${area}*F000.gif 20$todaym4/images/models/$grid/$cgrid${diag}_${area}*F000.gif 20$todaym3/images/models/$grid/$cgrid${diag}_${area}*F000.gif 20$todaym2/images/models/$grid/$cgrid${diag}_${area}*F000.gif 20$todaym1/images/models/$grid/$cgrid${diag}_${area}*F000.gif 20$yr$mn$dy/images/models/$grid/$cgrid${diag}_${area}*F000.gif 20$yr$mn$dy/images/models/$grid/$cgrid${diag}_${area}20$yr$mn$dy${hr}F00[3-6].gif
endif
