#!/bin/bash
set -e

if [ $# -lt 2 ]
then
  echo "ROBEX requires at least 2 arguments"
  echo "USAGE:"
  echo "  $0 inputFile strippedFile [outputMaskFile] [seed] "
  exit $E_BADARGS
fi

exiterr(){ echo -e "$@" >&2 && exit 1; }

# if we do not have `readlink -f` (os x, bsd): make our own readlink 
# this function is used to
#  1. make absolute paths
#  2. find the actual location of a symlinked script ($0) so we can find the dat folder
# it does not emulate the recursive path unlinking of `realpath -f`
# instead, it only follows the link of last directory  -- which should be enough to find the dat file
realreadlink=$(which readlink)
[ -z "$realreadlink" ] && exiterr "the 'readlink' program is not installed on your system. $0 cannot be run!"
if ! readlink -f test >/dev/null 2>/dev/null; then
 readlink() { 
   [ "$1" == "-f" ] && shift # skip to the next thing if we have "-f"
   #[ ! -e "$1" ] && exiterr "$1 does not exist!"
   path="$(cd $(dirname "$1");pwd)"
   rp=$($realreadlink "$path") # returns empty if not a link
   [ -z "$rp" ] && rp="$path"
   fullpath="$path/$(basename "$1")"
   echo "$fullpath"
 }
fi

# Absolute path to output script
SCRIPT=$(readlink -f $0)
# Absolute path this script is in
SCRIPTPATH=`dirname $SCRIPT`
# Absolute path to input
INPUT=$(readlink -f $1)
# Absolute path to output1
OUTPUT1=$(readlink -f $2)
# Absolute path to output2 (if it is there)
if [ $# -gt 2 ]
then
	OUTPUT2=$(readlink -f $3)
else
	OUTPUT2=""
fi

cd $SCRIPTPATH
if [ $# -gt 3 ]
then
	cmd="./ROBEX $INPUT $OUTPUT1 $OUTPUT2 $4"
else
	cmd="./ROBEX $INPUT $OUTPUT1 $OUTPUT2"
fi

eval $cmd

exit

