#!/bin/bash -vx
###############################################################################
#
# cutest2matlab_osx: build the bridge between CUTEst and Matlab on OSX
# without relying on Matlab gfortran support
#
# Adapted from cutest2matlab by D. Orban, June 2017. Original version by
# Nick Gould for GALAHAD Productions, January 2013
#
###############################################################################

function help() {
  echo 'Use this script on OSX with gfortran and Matlab R2016a or later.'
  echo 'The script *may* work with earlier versions of Matlab but was not tested.'
  echo
  echo "Use: $(basename $0) PROBLEM[.SIF]"
  exit 0
}

[[ $# > 0 && ("$1" == '-h' || "$1" == '--help') ]] && help

if [[ -z "$MYMATLABARCH" ]]; then
  if [[ -z "$MYARCH" ]]; then
    echo ' neither environment variable MYMATLABARCH nor MYARCH is set.'
    echo ' Set MYMATLABARCH as a gfortran-installed version from the list '
    /bin/ls -1 $CUTEST/versions 2>/dev/null
    echo ' and re-run.'
    exit 1
  else
    ARCH=${MYARCH}
  fi
else
  ARCH=${MYMATLABARCH}
fi

#  check that the architecture provided in MYMATLABARCH or MYARCH exists

if [[ ! -e $CUTEST/versions/$ARCH ]] ; then
    echo ' The architecture privided by the environment variables MYMATLABARCH'
    echo '  and MYARCH has not been installed. Install a gfortran version of'
    echo ' CUTEst unsing install_cutest and re-run.'
    exit 2
fi

#  check that a gfortran version is used (as this is what Matlab supports!)

if [[ ${ARCH##*.} != 'gfo' && ${ARCH##*.} != 'gfo47' ]] ; then
    echo ' The architecture privided by the environment variables MYMATLABARCH'
    echo ' (or otherwise MYARCH) must use the gfortran compiler. Install a '
    echo ' gfortran version of CUTEst unsing install_cutest and re-run.'
    exit 3
fi

. ${ARCHDEFS}/compiler.${ARCH}

# decode
[[ $# > 0 ]] && sifdecoder -A $ARCH $1

# build small shared library specific to problem being decoded
EXTERF=$([[ -f "EXTER.f" ]] && echo "EXTER.f" || echo "")
EXTERO=$([[ -f "EXTER.f" ]] && echo "EXTER.o" || echo "")
${FORTRAN} ${BASIC} ${F77} -I${CUTEST}/modules/${MYARCH} ELFUN.f RANGE.f GROUP.f $EXTERF
PROB=$(basename $1 .SIF)
${FORTRAN} -shared -undefined dynamic_lookup -o lib${PROB}.dylib ELFUN.o RANGE.o GROUP.o $EXTERO

# build and link mex file
[[ -f ${PWD}/mcutest.o ]] || ${MYMATLAB}/bin/mex -c -I${CUTEST}/include ${CUTEST}/src/matlab/mcutest.c
${MYMATLAB}/bin/mex -I${CUTEST}/include -output mcutest -L${PWD} -l${PROB} -lcutest  mcutest.o

exit 0
