#!/bin/bash

# -----------------------------------------------------------------
# RPC Project :
# Run RPC_give_spin_dir_CLUSTER : give spin direction in GEI system from STAFF
# P. Robert, LPP, 2014-02-15
# -----------------------------------------------------------------

appli=`basename $0`
appli36=`echo "$appli                                 " | cut -c1-36`
Narg=4

if( (test $# = 1 ) && (test $1 = -h ) ) ; then hh=1 ; else hh=0 ; fi

if test $# != $Narg || test $hh = 1
   then
   echo "$appli : give spin direction in GEI system"
   echo "$appli   require $Narg argument(s), ex:"
   echo "$appli   SatNum year month day"
   echo " "
   echo "     SatNum        : Sat numbert (1-4)"
   echo "     year month day: date"
   echo ""
   echo "example:"
   echo "$appli 3 2001 09 23 "
   echo ""
   if test $hh = 1 ; then exit 0 ; fi
   echo " $appli36 : *** ERROR ! Command aborted." >&2
   exit 1
fi

SatNum=$1
year=$2
month=$3
day=$4

# Spacecraft test
# ---------------

if ((test $SatNum -lt 1 ) || (test $SatNum -gt 4 ))
   then 
        echo "S/C # must be >=1 and =< 4"
        echo " $appli36 : *** ERROR ! Command aborted." >&2
        exit 2
fi

# search a CLUSTA file corresponding to given date

if test -f toto_$$.tmp ; then rm toto_$$.tmp ; fi

for BitRate in NBR HBR
    do
    dir1=$R_RFF_data_CLU/STA/VTL1/$BitRate/$repere/$year/$year"_"$month
    ls $dir1/CLU$SatNum*STA*VTL1*$year$month$day*.rff > toto_$$.tmp 2> /dev/null
    if test $? = 0 
       then break 
    fi

    for repere in ISR2 GSE
        do
        dir2=$R_RFF_data_CLU/STA/VTL2/$BitRate/$repere/$year/$year"_"$month
        ls $dir2/CLU$SatNum*STA*VTL2*$year$month$day*.rff > toto_$$.tmp 2> /dev/null
    if test $? = 0 
       then break 2
    fi
    done

done

if test -f toto_$$.tmp 
   then filrff=`head -1 toto_$$.tmp`
   else echo "no CLUSTA file for this date in rff_data_base"
        echo " $appli36 : *** ERROR ! Command aborted." >&2
        exit 3
fi

# recherche des donnees dans le fichier VTL1 ou VTL2

head -200 $filrff  | \
grep -e "VAR SPIN_GEI_RIGHT_ASCENSION" \
     -e "VAR SPIN_GEI_DECLINATION" \
     -e "VAR SPIN_PERIOD" 
     
if test $? != 0
   then
      echo "file $fildir/$filrff :"
      echo "data not found"
      echo " $appli36 : *** ERROR ! Command aborted." >&2
      exit 4
fi
echo "Done !"
echo " $appli36 : NORMAL TERMINATION - time exe= $diff s." >&2
