#!/bin/bash 
#!-*-sh-*-
#==============================================================
#
#  Abs:  Wraps matlab for FACET. 
#
#  Name: fmatlab
#
#  Facility:  SLAC/FACET
#
#  Rem: Moves the java.opts_facet matlab initalization file, from 
#       its referece area to the working directory, and renames it
#       to java.opts, so that matlab uses it. When matlab exits,
#       the copied java.opts is deleted.
#
#  Auth: 18-May-2011, Greg White (greg)
#  Rev:  dd-mmm-yyyy, Reviewer's Name     (USERNAME)
#
#--------------------------------------------------------------
#  Mod:
#
#==============================================================

BAD_DIR=1;
NOJAVAOPTS=2;
MATSTAT_ROGUE=999
matstat=$MATSTAT_ROGUE  

# Define LCLS_ROOT, based on AFS for development or NFS for production,
# since matlab setup things are under LCLS_ROOT, including java.opts   
if [ -d /afs/slac/g/lcls ]; then 
	export LCLS_ROOT=/afs/slac/g/lcls
else
        export LCLS_ROOT=/usr/local/lcls
fi

# Protect against someone running matlab in a protected area. 
if [ x"${PWD}" == x"${LCLS_ROOT}*" ]; then
	echo 'You must not be under $FACET_ROOT to run matlab for facet'
	exit $BAD_DIR;
fi
 
if [ -f ${LCLS_ROOT}/tools/matlab/setup/java.opts_facet ]; then   
	wd=${PWD}	
        cp ${LCLS_ROOT}/tools/matlab/setup/java.opts_facet ${wd}/java.opts
	matlab -glnx86 -nosplash $@ 
	matstat=$?
	if [ -f ${wd}/java.opts ]; then
		rm -f ${wd}/java.opts
	fi
else
	echo 'No java.opts_facet found, exiting'
	exit $NOJAVAOPTS;
fi 

# Exit with the status matlab exited with, unless matlab was never exited.
if [ $matstat != $MATSTAT_ROGUE ]; then
	exit $matstat
fi

# All other exits
exit 0;
