#!/bin/csh -f

# Input L0 file
# Return temporary ephemeris filename

# Get base directory
set dir=$2

set L0filename=`basename $1`
set times=`grep $L0filename $AQUARIUS_DATA/L0/tempL0_319_347.db`

# Determine YYYY/DOY 100 minutes before start time
set day1=`echo $times | cut -d "|" -f2`
set sec=`date -u -d "$day1" +%s`
@ sec1 = $sec - 6000
set dte1=`date -u -d "1970-01-01 $sec1 seconds" +%Y/%j`

# Determine YYYY/DOY 100 minutes after stop time
set day2=`echo $times | cut -d "|" -f3`
set sec=`date -u -d "$day2" +%s`
@ sec2 = $sec + 6000
set dte2=`date -u -d "1970-01-01 $sec2 seconds" +%Y/%j`

#echo $day1 $dte1
set ephname="SAC-D_PREDEPHEM_MJ2K_XYZ_"
set ephfile1=`ls -1 ${dir}/ephatt/${dte1}/${ephname}*.TXT`
set ephfile2=`ls -1 ${dir}/ephatt/${dte2}/${ephname}*.TXT`
set ephfiles=( $ephfile1)
if ( $ephfile1 != $ephfile2) then
    set ephfiles=( $ephfiles $ephfile2)
endif

echo $ephfiles > tmp.$$
#exit

# Sort and remove duplicates
set fle=`sort tmp.$$ | uniq`
echo $fle > tmp.$$

# Compute number of records in concatenated ephem file
@ nrec = 0
foreach i (`cat tmp.$$`)
    set n=`grep HEADER $i | cut -c 20-25`
    @ nrec = $nrec + $n
end

rm eph.$$ >& /dev/null

# Write # of records in concatenated ephem file
echo $nrec >> eph.$$

#echo tmp.$$

# Write records to concatenated ephem file
foreach i (`cat tmp.$$`)
   grep -v HEADER $i >> eph.$$
end

#rm tmp.$$ >& /dev/null

# Echo temporary eph filename
echo eph.$$

exit
