#!/bin/bash -f
# Sample simulator to Dakota system call script
# See User Manual for instructions

# $argv[1] is params.in.(fn_eval_num) FROM Dakota
# $argv[2] is results.out.(fn_eval_num) returned to Dakota

if [ -e $2 ]
then
    exit
fi

#check ISSM_DIR global variable is defined!
if [[ "$ISSM_DIR" == "" ]]
then
	echo "Dakota could not find the ISSM_DIR global variable ! Aborting..."
	exit 1
fi

# ------------------------
# Set up working directory
# ------------------------
num=`echo $1 | sed 's/params.in.//g'`

mkdir workdir.$num
cp Qmu.model workdir.$num
cp $ISSM_DIR/startup.m workdir.$num
cd workdir.$num
echo -n "$num" > number


# --------------
# PRE-PROCESSING
# --------------
# Use the following line if SNL's APREPRO utility is used instead of DPrePro.
# ../aprepro -c '*' -q --nowarning modal.bdf.template modal.bdf

#Preprocess 
dprepro ../$1 ../qmu.m cielo_ice_run.m

# --------
# ANALYSIS
# --------

#nast707 jid=modal.bdf mem=2m scr=yes bat=no >&! nastran.out
#cp -p ../cielo_ice_run.m .
matlab -nodisplay -r "cielo_ice_run('Qmu.model','$2');exit;" >& matlab.out.$num

# ---------------
# POST-PROCESSING
# ---------------

#grep '                                  X           ' modal.f06 | cut -c 46-60 > $2
#grep '        7        ' modal.f06 | cut -c 66-80 >> $2
mv $2 ../.
mv matlab.out.$num ../.

# --------
# Clean up
# --------

cd ..
rm -rf workdir.$num
