#! /bin/sh
#
# $Id: //depot/offshore/Riflex/riflex_4.6/etc/vrr#3 $
#
# This is a script for running multiple RIFLEX modules.
# The script riflex-c on the same directory is used.
#

# Initialize
istat=99

bindir="`dirname $0`"


# Usage
if   [ $# -lt 2 -o "$1" = "-h" -o "$1" = "--help" ]
then
   echo "Usage:  `basename $0` [-ht] modules pre1 [pre2 datadir]"
   echo "        using bindir $bindir                           "
   echo "Options:                                               "
   echo "  -h, --help -- show this help text                    "
   echo "  -t, --tidy -- delete RIFLEX binary result files after"
   echo "        successful analysis, *_if[nr]???.@(sam|ffi|raf)"

   istat=1
   exit $istat
fi


# Decode options
ltidy=0

while [ -n "`echo $1 | grep -e '^-' -e ' -' `" ]
do

   if   [ "$1" = "-t" -o "$1" = "--tidy" ]
   then
      ltidy=1
      shift 1

   elif [ -n "`echo $1 | grep -e '^-' -e ' -' `" ]
   then
      echo "Illegal option $1 found!" >&2
      exit 2

   fi
done


# Get input
mods=$1
output=`echo "isop isdop isdfop isvdop isdtop isvdtop" | grep "$mods" `
if [ -z "$output" ]
then
   istat=1
   echo
   echo "Illegal RIFLEX modules $mods"
   exit $istat
fi

pre1="`echo $2 | sed s/_$//`"
pre2="$pre1"
if   [ $# -ge 3 ]
then
   pre2="`echo $3 | sed s/_$//`"
fi

if   [ $# -ge 4 ]
then
   tmp="$4"
   echo "Using input value: $tmp"
elif [ ! -z "$RIFLEX_TMP" ]
then
   echo "Using global variable RIFLEX_TMP: $RIFLEX_TMP"
   tmp="$RIFLEX_TMP"
else
   tmp=""
fi


# Run modules INPMOD - OUTMOD
for i in i s v d f t o
do
   if [ -n "`echo $mods | grep $i`" ]
   then
      $bindir/riflex-c $i $pre1 $pre2 $tmp
      istat=$?
      if [ $istat -ne 0 ]
      then
         exit $istat
      fi
   fi
done


# Run PLOMOD
if [ -n "`echo $mods | grep p`" ]
then
   $bindir/riflex-c p
   istat=$?
   if [ $istat -ne 0 ]
   then
      exit $istat
   fi
fi


# Tidy? I.e. delete .ffi .sam. and .raf files
if [ $ltidy -eq 1 ]
then
   if   [ -d "$tmp" ]
   then
      pred="$tmp/"
   elif [ -n "$tmp" ]
   then
      pred="${tmp}_"
   else
      pred=""
   fi

   pref="`echo ${pred}${pre1} | sed -e s%//%/%g -e s/'_$'//`"
   rm -f ${pref}_ifn???.sam >/dev/null 2>&1
   rm -f ${pref}_ifn???.ffi >/dev/null 2>&1
   rm -f ${pref}_ifr???.raf >/dev/null 2>&1

   if [ "$pre2" != "$pre1" ]
   then
      pref="`echo ${pred}${pre2} | sed -e s%//%/%g -e s/'_$'//`"
      rm -f ${pref}_ifn???.sam >/dev/null 2>&1
      rm -f ${pref}_ifn???.ffi >/dev/null 2>&1
      rm -f ${pref}_ifr???.raf >/dev/null 2>&1
   fi
fi


# Exit
exit $istat
