#!/bin/csh -f

# Runs L2BIN one swath (L2 file) at a time (like spacebin)

set A1 = `echo $1 | grep parfile= | cut -d"=" -f2`
echo $A1

set in = `grep -i '^IN=' $A1 | cut -d= -f2`
set resolve = `grep -i '^RESOLVE=' $A1 | cut -d= -f2`
set prod = `grep -i '^L3BPROD=' $A1 | cut -d= -f2`
set flaguse = `grep -i '^FLAGUSE=' $A1 | cut -d= -f2`

echo "+-------------------------------------------------------------------+"
echo "Parameters:"
echo "-----------"
echo "IN=$in"
echo "RESOLVE=$resolve"
echo "L3BPROD=$prod"
echo "FLAGUSE=$flaguse"
echo "+-------------------------------------------------------------------+"

set basein = `basename $in`

set hr = `echo $basein | cut -c 9-10`
set day = `echo $basein | cut -c 2-8`

@ dy=$day

set prefix = `echo $basein | cut -d. -f1`
set suffix = `echo $basein | cut -d. -f2 | sed 's/L2/L3b/'`
set lab = ${prefix}-${dy}.${suffix}

@ tries = 0
set stats = (0 0)

echo "Initial pass for day $dy"
l2bin infile=$in \
	   ofile=$lab sday=$dy eday=$dy resolve=$resolve \
	   flaguse=$flaguse l3bprod=$prod rowgroup=180 interp=1
set stats[1] = $status
echo "Completed with status = $stats[2]"
@ tries++

if ( ($stats[1] == 0 || $stats[1] == 110) && $hr < 4) then

   echo "Decrementing day for a second pass"
   @ dy--

   set lab=${prefix}-${dy}.${suffix}

   l2bin infile=$in \
	      ofile=$lab sday=$dy eday=$dy resolve=$resolve \
	      flaguse=$flaguse l3bprod=$prod rowgroup=180 interp=1
   set stats[2] = $status
   echo "Completed with status = $stats[2]"
   @ tries++

else if ( ($stats[1] == 0 || $stats[1] == 110) && $hr > 19) then

   echo "Incrementing day for a second pass"
   @ dy++    

   set lab=${prefix}-${dy}.${suffix}

   l2bin infile=$in \
	      ofile=$lab sday=$dy eday=$dy resolve=$resolve \
	      flaguse=$flaguse l3bprod=$prod rowgroup=180 interp=1
   set stats[2] = $status
   echo "Completed with status = $stats[2]"
   @ tries++

endif

#
# Derive exit status
#
@ rtrn = ($stats[1] + $stats[2]) / $tries

if ($rtrn == 55) then
   # Case of 2 tries, 1 no data to bin and 1 successful completion
   @ rtrn = 0
endif

exit $rtrn

