#!/usr/bin/env bash
#
# Command Line Interface for SPM
# SPM: https://www.fil.ion.ucl.ac.uk/spm/
#
# Guillaume Flandin
# Copyright (C) 2023 Wellcome Centre for Human Neuroimaging


# Environment variables that can be used by this script:
# MATLAB_EXEC - name (and path) of the MATLAB executable
# MCR_HOME    - directory containing the MATLAB Runtime
# SPM_HOME    - directory containing (standalone) SPM
# OCTAVE_EXEC - name (and path) of the Octave executable


for arg in "$@"
do
  shift
  case "${arg%%=*}" in
    MATLAB_EXEC|MCR_HOME|SPM_HOME|OCTAVE_EXEC)
    eval export "${arg}"
    ;;
  *)
    set -- "$@" "$arg"
    ;;
  esac
done

if [[ ${MATLAB_EXEC} ]]; then
  "${BASH_SOURCE%/*}"/spm-matlab $@
  exit 0
fi

if [[ ${MCR_HOME} ]]; then
  "${BASH_SOURCE%/*}"/spm-mcr $@
  exit 0
fi

if [[ ${OCTAVE_EXEC} ]]; then
  "${BASH_SOURCE%/*}"/spm-octave $@
  exit 0
fi

if [ "$(command -v matlab)" != "" ]; then
  "${BASH_SOURCE%/*}"/spm-matlab $@
  exit 0
fi

if [ "$(command -v octave)" != "" ]; then
  "${BASH_SOURCE%/*}"/spm-octave $@
  exit 0
fi

echo "spm: no runtime engine found." >&2
exit 1
