#!/bin/bash

# -----------------------------------------------------------
# RPC Project :
# Run RPC_reduce_time_vectime : reduce the time period of a vectime file
# P. Robert, LPP, 2011-05-27
# -----------------------------------------------------------

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

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

if test $# != $Narg || test $hh = 1
   then
   echo "$appli : reduce the time period of a RFF file"
   echo "$appli   require $Narg argument(s), ex:"
   echo "$appli   toto_VT.rff toto_VT.rff datiso1 datiso2"
   echo "    toto_VT.rff : name of an input  vectime RFF file"
   echo "    toto_VT.rff : name of an output vectime RFF file"
   echo "    datiso1 datiso2 : date in ISO format"
   echo "    ex: 2001-09-23T09:00:39.504Z"
   echo "    ex: (works also on WF RFF files)"
   echo ""
   if test $hh = 1 ; then exit 0 ; fi
   echo "$appli36 : *** ERROR ! Command aborted." >&2
   exit 1
fi


if test $3 = $4
   then echo "first and end date are the same, copy entire file"
   cp $1 $2
   exit
fi

datiso1=`grep BLOCK_FIRST_INDEX $1 | cut -c38-`
datiso2=`grep BLOCK_LAST_INDEX  $1 | cut -c38-`

if test  $3 = $datiso1  && test  $4 = $datiso2 
   then echo "first and end date are the same that the file, copy entire file"
   cp $1 $2
   exit
fi

datim1=`date +%F'  '%H':'%M':'%S `
julsec1=`date +%s`

# remove RPC_ from RPC command

appli=`echo $appli | cut -c5-`

# creating appli.in from arguments list

if test -f $appli.in ; then \mv $appli.in $appli.in.old ; fi

for i in $*
    do
    echo $i >> $appli.in
done

# run appli.exe 

. run_appli.bash $appli
err=$?

alarm=" *** last command: abnormal termination - Command aborted" >&2
if test $err != 0 ; then echo "$alarm" ; exit $err ; fi

cat data.tmp                  >> $2
rm data.tmp
