function out = load( job, varargin )
%LOAD Load workspace variables from batch job
%   LOAD(JOB) retrieves all variables from a batch job that runs a script,
%   and assigns them into the current workspace. LOAD throws an error if
%   the batch job runs a function, if the job is not finished, or if the
%   job encountered an error while running.
%
%   LOAD(JOB, 'X') loads only the variable named X from the job.
%
%   LOAD(JOB, 'X', 'Y', 'Z')  loads only the specified variables.  The
%   wildcard '*' loads variables that match a pattern.
%
%   LOAD(JOB, '-REGEXP', 'PAT1', 'PAT2') can be used to load all variables
%   matching the specified patterns using regular expressions. For more
%   information on using regular expressions, type "doc regexp" at the
%   command prompt.
%
%   S = LOAD(JOB, ...) returns the contents of JOB in variable S. S is a
%   struct containing fields matching the variables retrieved.
%
%   Examples for pattern matching:
%       load(job, 'a*')                % Load variables starting with 'a'
%       load(job, '-regexp', '\d')     % Load variables containing any digits

% Copyright 2011-2017 The MathWorks, Inc.

job.errorIfNotBatch();

try
    % Convert any string inputs to character vectors
    [varargin{:}] = convertStringsToChars(varargin{:});
    
    workspaceOut = parallel.internal.apishared.BatchJobMethods.load( ...
        job, varargin{:} );
catch E
    throw( E );
end

if nargout == 0
    % Get the output variable names
    varNamesOut = fieldnames(workspaceOut);
    % Next populate with the required variables
    for i = 1:numel(varNamesOut)
        assignin('caller', varNamesOut{i}, workspaceOut.(varNamesOut{i}));
    end
else
    out = workspaceOut;
end
end
