#!/bin/bash
# This script pre-processes the Fortran source code for sunf95 and g95. They do not allow passing
# internal procedures as actual arguments, but the MEX gateways need to do so for CALFUN and CALCFC.

DIR="$(realpath "$1")"

if ! basename "$DIR" | grep -q ".test\|test." || ! [[ -d "$DIR" ]] ; then
    printf "\n%s is not a testing directory.\n\nExit.\n\n" "$DIR"
    exit 1
fi

SOLVER="$(basename "$DIR" | sed 's/test\.//' | sed 's/\.test//')"
MEXF="$DIR"/"$SOLVER"_mex.F90
TMPF=/tmp/"$(date +%s)"

if [[ "$SOLVER" == "cobyla" ]] ; then
    CBFUN="calcfc"
    FPTR="funcon_ptr"
else
    CBFUN="calfun"
    FPTR="fun_ptr"
fi

# Replace the line starting with "mwPointer :: $FPTR" by "external :: $CBFUN".
sed -i "s/^\s*mwPointer\s*::\s*$FPTR/external\ ::\ $CBFUN/" "$MEXF"

# Remove the line starting with "$FPTR = ".
sed -i "/^\s*$FPTR\s*=/d" "$MEXF"

# Remove all the lines below the line starting with "contains".
sed -n "/^\s*contains/q;p" "$MEXF" > "$TMPF"
cat "$TMPF" > "$MEXF"
# Append "end subroutine" to the end, because it was removed above.
echo "end subroutine mexFunction" >> "$MEXF"

exit 0
