function restoreVerbosity = setPCTVerbosity(level)
% SETPCTVERBOSITY Sets PCT verbosity level and returns a Cleanup object. 
% When destroyed, this Cleanup object restores PCT verbosity to the same 
% level as before SETPCTVERBOSITY was called.
%
% restoreVerbosity = SETPCTVERBOSITY(level) sets PCT verbosity level to
% level and returns a Cleanup object.
%
% level must be a positive integer.

%   Copyright 2020 The MathWorks, Inc.

narginchk(1, 1);

if nargout ~= 1
    error(message('parallel:internal:InvalidVerbosityOutput'));
end

validateattributes(level, {'numeric'}, {'nonnegative', 'scalar', 'integer'});

originalLevel = getenv('PCT_VERBOSITY');
restoreVerbosity = onCleanup(@() setenv('PCT_VERBOSITY', originalLevel));
newlevel = num2str(level);
setenv('PCT_VERBOSITY', newlevel);
end