function [ret] = mpsPctPatchJobStorageLocation

% Copyright 2015 The MathWorks, Inc.
%
% This function iterates through each PCT profile and appends the process ID to
% the JobStorageLocation. It is meant to be called by MPS in order to support
% the simultaneous use of PCT by multiple workers. Otherwise, they will use
% the same location and cause sporadic failures. The JobStorageLocation is only
% modified for the session.

try
    ret = 1 ;
    
    % Make sure that this can run in normal MATLAB as well as deployed MCR's
    if ~(isdeployed || parallel.internal.settings.qeDeployedOverride)
        parallel.internal.settings.qeDeployedOverride(true);
    end
    
    % Using parallel.Settings find the scheduler component for each profile
    S = parallel.Settings;
    profiles = S.findProfile;

    uniqueEndingStr = num2str(feature ('getpid'));

    % Loop for each profile
    for index = 1:numel(profiles)
        sc = profiles(index).getSchedulerComponent;
        
        % Check if the scheduler component has a JobStorageLocation property that
        % we need to append to
        if ~isprop(sc, 'JobStorageLocation')
            continue
        end
        
        % Get the value at the user level (in case you've already called this
        % function once and set the value at the session level)
        baseDir = get(sc, 'JobStorageLocation', 'user');
       
        % If it isn't a string we will create a specific local cluster which will
        % have the correct default location and append to that instead
        if ~ischar( baseDir )
            l = parallel.cluster.Local;
            baseDir = l.JobStorageLocation;
        end

        dataLoc = fullfile(baseDir, uniqueEndingStr);
        
        % Directory must exist
        if ~exist(dataLoc, 'dir')
            mkdir (dataLoc);
        end

        % Importantly, we are only making the change to the settings for this session
        set(sc, 'JobStorageLocation', dataLoc, 'session')
    end
    
catch err
    fprintf ('patchPctJobStorageLocation: INTERNAL ERROR: %s', err.message) ;
    ret = 0 ;
end
