function distcomp_evaluate_filetask(varargin)
%

% Copyright 2005-2021 The MathWorks, Inc.

try
    logLevel = parallel.internal.logging.getWorkerLogLevel();
    debugEnabled = logLevel > 0;
    setSchedulerMessageHandler(iMessageHandler(logLevel));

    % If this a deployed (local) worker then we need to tell the deployed 
    % application not to simply exit when distcomp_evaluate_filetask returns - 
    % if the task is part of a parallel pool then the worker needs to remain
    % alive after this function returns
    iPreventDeployedWorkerExiting();
    
    distcomp_evaluate_filetask_core(debugEnabled, varargin{:});
catch err
    dctSchedulerMessage(0, 'Evaluating task with DistcompEvaluateFileTask failed, the error was: ', err);
    iAllowDeployedWorkerToExit();
    parallel.internal.cluster.exitOnException(1);
end
end

%--------------------------------------------------------------------------
%
%--------------------------------------------------------------------------
function handler = iMessageHandler(desiredLevel)

handler = @nHandler;

    function nHandler(msg, messageLevel)
        if messageLevel > desiredLevel
            return;
        end    

        % This handler puts messages to stdout (via fprintf) which are
        % captured by the MATLAB logfile redirect
        fprintf('%s | %s\n', datestr(now, 31), msg)
    end
end

%--------------------------------------------------------------------------
%
%--------------------------------------------------------------------------
function iPreventDeployedWorkerExiting()
% If this is a parallel pool job then we need the deployed worker process
% to remain alive after distcomp_evaluate_filetask returns - the default behaviour
% is for a deployed application to exit when the main function returns.
if isdeployed
    parallel.internal.cluster.workerShutdown('prevent');
end
end

%--------------------------------------------------------------------------
%
%--------------------------------------------------------------------------
function iAllowDeployedWorkerToExit()
% Allow the deployed worker to exit. 
% If this was a parallel pool job this means the worker process can now exit. If 
% it was a normal job then the worker process will exit when 
% distcomp_evaluate_filetask returns.
if isdeployed
    parallel.internal.cluster.workerShutdown('allow');
end
end
