function varargout = executeFunction(fcn, fcnNumArgsOut, fcnArgsIn, workerCwdPathInfo)
%

%  Copyright 2010-2017 The MathWorks, Inc.

dctSchedulerMessage( 5, '> executeFunction' );


% NB It is very important that the number of output arguments requested from
% executeFunction is EQUAL to the number of output arguments that the user originally
% requested for fcn.  Note that only PCT code calls executeFunction, so this is just 
% a sanity check.
if nargout ~= fcnNumArgsOut
    fcnName = fcn;
    if isa(fcn, 'function_handle')
        fcnName = func2str(fcn);
    end
    error(message('parallel:convenience:BatchInconsistentNumberOfOutputArguments', nargout, mfilename, fcnNumArgsOut, fcnName));
end

parallel.internal.cluster.tryToChangeDirectory(workerCwdPathInfo);

% MATLAB is not good at asking for zero output arguments, try for example 
% clear
% [x{1:0}] = feval(@matlabroot)
% So we will distinguish between fcnNumArgsOut == 0 and anything else
if fcnNumArgsOut > 0
    varargout = cell(fcnNumArgsOut, 1);
    [varargout{1:fcnNumArgsOut}] = feval(fcn, fcnArgsIn{:});
else
    feval(fcn, fcnArgsIn{:});
end
dctSchedulerMessage( 5, '< executeFunction' );
