#!/bin/sh
#
# Command Line Interface for SPM
# SPM: http://www.fil.ion.ucl.ac.uk/spm/
#
# Copyright (C) 2017 Wellcome Trust Centre for Neuroimaging
#
# Guillaume Flandin
# $Id: spm12-matlab 7014 2017-02-13 12:31:33Z guillaume $ 

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" ]; 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" ]; 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
