#MatLab Batch Job Front End
#Ben Marlin - marlin[at]cs[dot]toronto[dot]edu
#
#Description: To start this program from the command line
#in interactive mode type 'bash batch_matlab'. To start
#the program in non-interactive mode enter 
#'bash batch_matlab <input file> <output file>' where 
#<input file> is the path to the matlab m-file you 
#want to run, and <output file> is the path to the file
#matlab session output will be saved to. 
#
#Warning: in non-interactive mode, if the output file exists 
#it will be overwritten.
#

params=2
outputformat=">>" #default output foramt. > overwrites. >> appends.

#
#If user entered command line options, 
#suppress interactive mode and start job.
#
if [ "$params" -eq $# ] 
then
 if [ -f "$1" ]
  then   
    `nohup matlab -nodisplay <$1 1>$2 2>1 &`
    echo "Job started with input $1, output $2." 
    exit
  else
    echo "Input file $1 does not exist."
    exit
  fi
fi

#
#Print tag line
#
echo ""
echo "MatLab Batch Job Front End"

#
#Get input file name
#
echo "Enter the path to the M-File you want to run:"
echo -n ">> "
read inputfile
if [ ! -f "$inputfile" ]
then
  echo "Input file $inputfile does not exist."
  exit
fi

#
#Get output file name
#
echo "Enter the path to the file you want to save output to:"
echo -n ">> "
read outputfile

#
#Check for output file
#
if [ -f "$outputfile" ]
then
  echo "Output file already exists. Overwrite or Append? [O/A]:"
  echo -n ">> "
  read outputtype
  if [ "$outputtype" = "O" -o "$outputtype" = "o" ]
  then
    outputformat=">"
  fi
fi  

#
# Get confirmation and start job
#
echo "Continue? [Y/N]":
echo -n ">> "
read cont

if [ "$cont" = "Y" -o "$cont" = "y" ]
then
  #launch matlab in the background with input piped in and 
  #output piped out
  `nohup matlab -nodisplay <$inputfile 1${outputformat}${outputfile} 2>1 &`
  echo "Job started"
else
  echo "Job cancelled."
fi

exit
