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

# This script makes use of the following environment variables:
#
# MCR_HOME - directory containing the MATLAB Runtime
#            [default: undefined]
# SPM_HOME - directory containing Standalone SPM
#            [default: parent directory of this script]


if [ "${SPM_EXE}" = "" ]; then
  SPM_EXE="run_spm.sh"
fi

if [ "${MCR_HOME}" = "" ]; then
  echo "MATLAB Runtime not found: set the MCR_HOME environment variable." >&2 
  exit 1
fi
if [ ! -d "${MCR_HOME}" ]; then
  echo "MATLAB Runtime not found: set the MCR_HOME environment variable." >&2 
  exit 1
fi

if [ "${SPM_HOME}" = "" ]; then
  if [ "${PLATFORM}" = "Darwin" ] || [ "${PLATFORM}" = "arm64" ]; then
    RL_FLAG="" # alternative needed
  else
    RL_FLAG="-f"
  fi
  SPM_HOME=$(readlink ${RL_FLAG} "$0")
  while [ ! -x "${SPM_HOME}/${SPM_EXE}" ]; do
    if [ "${SPM_HOME}" = "$(dirname "${SPM_HOME}")" ]; then
      echo "Standalone SPM not found: set the SPM_HOME environment variable." >&2 
      exit 1
    fi
    SPM_HOME=$(dirname "${SPM_HOME}")
  done
fi
if [ ! -d "${SPM_HOME}" ]; then
  echo "Standalone SPM not found: set the SPM_HOME environment variable." >&2 
  exit 1
fi
if [ ! -x "${SPM_HOME}/${SPM_EXE}" ]; then
  echo "Standalone SPM not found: set the SPM_HOME environment variable." >&2 
  exit 1
fi

"${SPM_HOME}"/${SPM_EXE} ${MCR_HOME} $@
