#!/bin/bash

# -------------------------------------------------------
# RPC Project :
# RPC_vectime_to_indexed_data
# P. Robert,  Feb. 2021
# -------------------------------------------------------

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

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

if test $# != $Narg || test $hh = 1
   then
   echo "$appli : create indexed_data file from a rff VT file" 
   echo "$appli   require $Narg argument(s), ex:"
   echo "$appli   tot1.rff toto.ind"
   echo "    toto.rff : VecTime RFF source file"
   echo "    toto.ind : indexed_data target file"
   echo ""
   if test $hh = 1 ; then exit 0 ; fi
   echo "$appli36 : *** ERROR ! Command aborted." >&2
   exit 1
fi

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


echo " -------------------------------------------------------------------"
echo " Run of $appli :"
echo " $appli $*"
echo
echo " create indexed_data file from a rff VT file without extended index"

# test if source file exists
if test -f $1
   then
       echo " "
   else 
       echo "*** RPC ERROR : File $1 does not exists"
       echo "$appli36 : *** ERROR ! Command aborted." >&2
       exit 2
fi

# test if source file is a rff
rff=`basename $1`
suff=`echo $rff |cut -d"." -f2`
if test $suff != rff 
   then
       echo "*** RPC ERROR : File $1 is not a rff"
       echo "$appli36 : *** ERROR ! Command aborted." >&2
       exit 3
fi

# test if source file is a VecTime
rff=`basename $1`
indexb=`grep FILE_CLASS $1 | cut -f2 -d:`
index=`echo $indexb | cut -c1-11`
if test $index != VecTime
   then
       echo "*** RPC ERROR : File $1 is not a VecTime rff"
       echo "$appli36 : *** ERROR ! Command aborted." >&2
       exit 3
fi

if test -f $2 ; then rm $2 ; fi

# extract indexed data without extended index

lex=`grep "PAR INDEX_EXTENSION_LENGTH    (INT):" $1 | cut -f2 -d:`
sed -n '/START INDEXED_DATA/,/END INDEXED_DATA/p' $1 > toto_$$.tmp
chaine=`sed -n '2p' toto_$$.tmp` 
posZ=`expr index "$chaine" Z`
skip=`expr $posZ + $lex`

nbloc=`grep "PAR BLOCK_NUMBER              (INT):" $1 | cut -f2 -d:`
sed 's/,//g' toto_$$.tmp | cut -c1-$posZ,$skip- | sed "1s/START INDEXED_DATA/$nbloc/" > $2

rm toto_$$.tmp

# end of command
# --------------

datim2=`date +%F'  '%H':'%M':'%S `
julsec2=`date +%s`
diff=`expr $julsec2 - $julsec1`

echo " Starting time $appli : $datim1"
echo " Ending   time $appli : $datim2"
echo " Duration      $appli : $diff sec."
echo
echo " $appli36 : NORMAL TERMINATION - time exe= $diff s." >&2

echo " -------------------------------------------------------------------"

