function oldDiscovery = currentDiscoveryManager(newDiscovery)
% currentDiscoveryManager Get or set the current discovery manager
% oldDiscovery = currentDiscoveryManager(newDiscovery)

%   Copyright 2012 The MathWorks, Inc.

persistent discoveryManager

if isempty(discoveryManager)
    discoveryManager = iGetDefaultDiscoveryManager();
end

oldDiscovery = discoveryManager;

if nargin > 0
    validateattributes(newDiscovery, {'parallel.internal.discover.DiscoveryManager'}, {'scalar'});
    discoveryManager = newDiscovery;
end
end

%-------------------------------------------------------------
function discoveryManager = iGetDefaultDiscoveryManager
    persistent defaultDiscoveryManager
    
    if isempty(defaultDiscoveryManager)
        % The default is the real one that includes all the discoverers in
        % the parallel.internal.discover.package
        defaultDiscoveryManager = parallel.internal.discover.DiscoveryManager();
        discovererConstructors = {@parallel.internal.discover.HPCServer, @parallel.internal.discover.MJS, ...
            @parallel.internal.discover.MJSComputeCloud};
        cellfun(@(x) defaultDiscoveryManager.registerDiscoverer(x()), discovererConstructors);
    end
    
    discoveryManager = defaultDiscoveryManager;
end
