function varargout = getbev(varargin)
%function varargout = getbev(varargin)
% This m-file GETs 3 runtime Batch Environment Variables:
% 1. nslots (=number of cores as determined by -pe omp nslots)
% 2. task (=SGE_TASK_ID of qsub -t; ='undefined' otherwise)
% 3. nthreads = nslots
%    This prevents system from aborting job. As a result,
%    matlab -singleCompThread is not required (but OK to use).
% Usages:
% nslots=getbev; [nslots,task]=getbev; [nslots,task,nthreads]=getbev;

if verLessThan('matlab', '8.5')
   warning off  % maxNumCompThreads supported at least until R2014b
else  % reminds if R2015 or newer
   disp('Check to see if maxNumCompThreads is still supported')
end

if ~isBatch
  disp('This is not a batch job')
  varargout(1) = {1};                 % nslots = 1
  varargout(2) = {'undefined'};       % task = 'undefined'
  varargout(3) = {maxNumCompThreads}; % nthds = max threads on node
  return
end

% 1. Check if parallel job (qsub -pe omp nslots)
nslots = getenv('NSLOTS'); 
if nslots == 'undefined' 
   nslots = 1;   % no -pe requested; default to 1 core
else
   nslots = str2double(nslots);   % convert string to double
end

% 2. Check if Array Jobs (qsub -t ...)
task = getenv('SGE_TASK_ID'); 
if ~strcmp(task, 'undefined')
   task = str2double(task);
end

% 3. Multithreads setting criteria:
mthreads = maxNumCompThreads();
if nslots == 1
  maxNumCompThreads(1);
  nthreads = 1;
else
  if mthreads > 1
    maxNumCompThreads(nslots); % -singleCompThread NOT imposed
    nthreads = nslots;
    fprintf(1,'Number of threads is set to be the requested %d slots\n', ...
          nthreads);
  else
    nthreads = 1;  % matlab -singleCompThread imposed
  end
end

varargout(1) = {nslots};
varargout(2) = {task};
varargout(3) = {nthreads};

end
