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


PLATFORM=$(uname)

if [ "${OCTAVE_EXEC}" = "" ]; then
  OCTAVE_EXEC="octave"
fi
if [ "$(command -v ${OCTAVE_EXEC})" = "" ]; then
  echo "Octave 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}"
addpath (canonicalize_file_name ("${SPM_HOME}"));

try
  spm ("Ver");
catch
  printf (["error: Cannot find the SPM directory. " ...
    "Set SPM_HOME environment variable.\n"]);
  exit (1);
end

spm_standalone (${INPUTS});

while (! isempty (get (0, "CurrentFigure")))
  waitfor (get (0, "CurrentFigure"));
endwhile
exit (0);

EOF

${OCTAVE_EXEC} --norc --quiet --no-history ${OCTAVE_FLAGS} --eval "run('${TMPFILE}');"
ERR=$?

rm -f "${TMPFILE}"

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