#!/bin/bash

if [ -z "$NSLOTS" ]; then
    NSLOTS=4
fi

#running case

rm -rf 0
cp -r org0 0

echo -n "creating FAMesh..."
if makeFaMesh > log.makeFaMesh; then
    echo "   OK"
else 
	echo "   FAILED"
	exit 1
fi

rm -rf constant/releaseArea
echo -n "writing releaseArea (h)"
if python ../../../../scripts/shape2dict.py \
-i rawdata/release.shp \
-o constant/releaseArea \
-f "h" \
-v 1.61 \
-z0 1289 \
-dfdz 0.0008 \
-offsetx "2000" \
-offsety "-221000" \
-d 1e-6
then
    echo "   OK"
else 
    echo "   FAILED"
    exit 1
fi
echo -n "setting releaseArea (h)"
if releaseAreaMapping > log.releaseAreaMapping_h; then
    echo "   OK"
else 
    echo "   FAILED"
    exit 1
fi

cp constant/releaseArea.hmsc constant/releaseArea
echo -n "setting releaseArea (hentrain/base)"
if releaseAreaMapping > log.releaseAreaMapping_hentrainbase; then
    echo "   OK"
else 
    echo "   FAILED"
    exit 1
fi

rm -rf constant/releaseArea
echo -n "writing releaseArea (hentrain)"
if python ../../../../scripts/shape2dict.py \
-i rawdata/release.shp \
-o constant/releaseArea \
-f "hentrain" \
-offsetx "2000" \
-offsety "-221000" \
-v 0
then
    echo "   OK"
else 
    echo "   FAILED"
    exit 1
fi
echo -n "setting releaseArea (hentrain)"
if releaseAreaMapping > log.releaseAreaMapping_hentrain; then
    echo "   OK"
else 
    echo "   FAILED"
    exit 1
fi

echo "writing decomposeParDict for N=$NSLOTS"
sed "s/N/$NSLOTS/g" system/decomposeParDict.org > system/decomposeParDict

echo "clearing oldData..."
rm -rf processor*

echo -n "running decomposePar"
if decomposePar > log.decomposePar; then
    echo "   OK"
else 
    echo "   FAILED"
    exit 1
fi

echo "running faSavageHutterFoam in parallel (N=$NSLOTS)"
if mpirun -np $NSLOTS faSavageHutterFoam -parallel | tee log.faSavageHutterFoam | grep "^Time*"; then
    echo "SIMULATION FINISHED"
else 
    echo "SIMULATION FAILED"
    exit 1
fi


echo -n "running reconstructPar"
if reconstructPar > log.reconstructPar; then
    echo "   OK"
else 
    echo "   FAILED"
    exit 1
fi