#!/bin/bash
if [ "$#" -lt 2 ] ; then
    echo "Script created by Boyan to submit Rmpi jobs that use the R.matlab"
    echo "Usage: $0 n your_script.r "
    echo "    n = number of required processor cores"
    echo "Job not submitted"
    exit 1
fi
NP=$1
shift
queue="$(/product/bin/utils/queue $0)"
source /product/intel/impi/4.1.0.024/intel64/bin/mpivars.sh
export R_PROFILE=/product/R/R-3.0-el6/lib64/R/library/Rmpi/Rprofile
eval exec bsub -n $NP << !
###BSUB -eo error.\${USER}.%J.txt
#BSUB -oo output.${USER}.%J.txt -N
#BSUB -q ${queue}
#BSUB -app R
#BSUB -J RMPI_Job

## copy over the files needed by the Matlab servers
rmatlab=/product/R/R-3.0-el6/lib64/R/library/R.matlab/externals
while read file ; do
    [[ -f \${file} ]] || cp \${rmatlab}/\${file} .
done << EOF
MatlabServer.m
InputStreamByteWrapper.class
InputStreamByteWrapper.java
EOF
unset rmatlab

## this is the base port number.  each process will add its own rank
export MATLABSERVER_PORT=\$(( 10000 + (\${LSB_JOBID} % 100) * 200 ))
mpiexec.hydra -bootstrap lsf /bin/bash -c \
"
    # start the matlab server for the current rank and put it in the background
    # do not start Matlab for the master (rank 0)
    if (( \\\${PMI_RANK:--1} > 0 )) ; then
        ((  MATLABSERVER_PORT += \\\${PMI_RANK}  ))
         matlab_cmd -nodisplay -singleCompThread -r MatlabServer \
             > output.matlab.\\\${LSB_JOBID:-0}.\\\${PMI_RANK}.txt 2>&1 &
        #matlab_cmd -nodisplay -singleCompThread -r MatlabServer \
        #    > /dev/null 2>&1 &
    fi

    # start the R process and keep it in the foreground
    exec /product/R/R-3.0.sh --slave -f $*
"
!



