#!/usr/bin/env bash
#
# Command Line Interface for SPM using MATLAB
# 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:
#
# MATLAB_EXEC - name (and path) of the MATLAB executable
#               [default: "matlab"]
# SPM_HOME    - directory containing an SPM installation
#               [default: parent directory of this script]


PLATFORM=$(uname)

if [ "${MATLAB_EXEC}" = "" ]; then
  MATLAB_EXEC="matlab"
fi
if [ "$(command -v ${MATLAB_EXEC})" = "" ]; then
  echo "MATLAB executable not found." >&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")
  SPM_HOME=$(dirname "$(dirname "${SPM_HOME}")")
fi
if [ ! -d "${SPM_HOME}" ]; then
  echo "SPM directory not found." >&2 
  exit 1
fi

INPUTS=""
for arg in "$@"
do
  INPUTS=${INPUTS}"'${arg//\'/\'\'}',"
done
if [ "${INPUTS}" != "" ]; then
  INPUTS=${INPUTS:0:$((${#INPUTS}-1))}
fi

if [ "${PLATFORM}" = "Darwin" ] || [ "${PLATFORM}" = "arm64" ]; then
  TMPFILE=$(mktemp -u -t spm)
  TMPFILE=${TMPFILE//./_}.m
else
  TMPFILE=$(mktemp --tmpdir -u spm_XXXXXX).m
fi
cat << EOF > "${TMPFILE}"
warning('off','backtrace');
cd(getenv('PWD'));
spm_dir = '${SPM_HOME}';
try, spm_dir = cd(cd(spm_dir)); end % canonical path
addpath(spm_dir);
try
  spm('Ver');
catch
  fprintf(['Error: Cannot find the SPM directory. ' ...
    'Set SPM_HOME environment variable.\n']);
  exit(1);
end
warning('on','backtrace');
spm_standalone(${INPUTS});
while ~isempty(get(0,'CurrentFigure'))
  waitfor(get(0,'CurrentFigure'));
end
exit(0);
EOF

${MATLAB_EXEC} -nosplash -nodesktop ${MATLAB_FLAGS} -r "run('${TMPFILE}');" | tail -n +11
ERR=${PIPESTATUS[0]}

rm -f "${TMPFILE}"

if [[ ${ERR} -eq 0 ]]; then
  exit 0
else
  exit 1
fi
