#!/bin/ksh
# Create a set of daily ASCII beacon files for a given spacecraft and year

. /home/stereo/Software/procenv

# aliases do not get passed down, so run this anyway
. /usr/local/rsi/idl_6.1/bin/idl_setup.ksh

YEAR=$1
SC=$2

if [ $SC != "ahead" -a $SC != "behind" ]; then
   echo Usage: $0 YYYY spacecraft, where spacecraft is either ahead or behind
   exit 1
fi

cd $STEREOIDL/SEPBeacon

# SEP Beacon data Version number
BVERSIONSTR=`awk '($1=="VERSION")&&($2=="="){print $3; exit}' sep_beacon_common.pro`
BVERSION=`expr "$BVERSIONSTR" : '\([0-9]*\)'`
if [ $BVERSION -lt 10 ]; then BVERSION=0$BVERSION; fi
export BVERSION

. /home/stereo/Software/procenv
export DESTDIR=$BEACONDATAHOME/$SC/$YEAR

if [ ! -d $DESTDIR ]; then
   $ECHO $0: making $DESTDIR
   mkdir -p $DESTDIR
fi


SDOY=1
EDOY=365

if [ $YEAR -eq 2006 -a $SC = "ahead" ]; then SDOY=318; fi
if [ $YEAR -eq 2006 -a $SC = "behind" ]; then SDOY=317; fi

if [ $YEAR -eq 2008 -o $YEAR -eq 2012 -o $YEAR -eq 2016 ]; then EDOY=366; fi

# echo $SDOY $EDOY

if [ $# -eq 3 ]; then
   echo Setting SDOY to $3
   SDOY=$3
fi

export IMPACT_CALIB_DATA=$STEREOIDL/SEPBeacon/calfiles
export YEAR SC

INDIR=$L0HOME/$SC/Subsetted

DOY=$SDOY
DOY=$((10#$DOY+0))
while [ $DOY -le $EDOY ]
do
   DOY3=$DOY
   if [ $DOY3 -lt 10 ]; then DOY3=0$DOY3; fi
   if [ $DOY3 -lt 100 ]; then DOY3=0$DOY3; fi

   INFILE=NoNoNo
   INFILE1=`/bin/ls $INDIR/misc_* | grep 'misc_'$SC'_'$YEAR'_'$DOY3'_.*.ptp' | tail -1`
   INFILE2=`/bin/ls $INDIR/misc_* | grep 'misc_'$SC'_'$YEAR'_'$DOY3'_.*.fin' | tail -1`
   if [ $INFILE1 ]; then INFILE=$INFILE1; fi
   if [ $INFILE2 ]; then INFILE=$INFILE2; fi
   if [ -f $INFILE ]; then
      echo $DOY3  $INFILE
      export DOY3 INFILE
      idl -quiet runbeacon.bat
   else
     echo No input file exists for ${YEAR}-$DOY3
   fi

   DOY=$(($DOY+1))
done
