function exportProfile(profileNames, filename)
%parallel.exportProfile Export one or more profiles to file
%   parallel.exportProfile(profileName, filename) exports the profile with the
%   name profileName to filename.  If filename has no extension, or the 
%   supplied extension is not .mlsettings, then the extension .mlsettings 
%   is appended to the filename.
%
%   parallel.exportProfile({profileName1, profileName2, ..., profileNameN}, filename)
%   exports the profiles with the specified names to filename.   If filename 
%   has no extension, or the supplied extension is not .mlsettings, then the 
%   extension .mlsettings is appended to the filename.
%
%   To import a profile, use parallel.importProfile() or the Cluster Profiles 
%   Manager.  On the Home tab, in the Environment section, click
%   Parallel > Create and Manage Clusters... to open the Cluster Profiles
%   Manager.
%
%   Examples:
%   Export the profile with name 'MyProfile' to file MyExportedProfile.mlsettings 
%     parallel.exportProfile('MyProfile', 'MyExportedProfile')
%
%   Export the default profile to file MyDefaultProfile.mlsettings 
%     def_profile = parallel.defaultProfile();
%     parallel.exportProfile(def_profile, 'MyDefaultProfile')
%
%   Export all profiles except for 'local' to file AllProfiles.mlsettings
%     allProfiles = parallel.listProfiles();
%     % Remove 'local' from allProfiles
%     notLocal = ~strcmp(allProfiles, 'local');
%     profilesToExport = allProfiles(notLocal);
%     if ~isempty(profilesToExport)
%       parallel.exportProfile(profilesToExport, 'AllProfiles');
%     end
%
%   See also parallel.defaultProfile, parallel.listProfiles, 
%   parallel.importProfile.

% Copyright 2011-2022 The MathWorks, Inc.

narginchk(2, 2);

% Convert any string inputs to character vectors
[profileNames, filename] = convertStringsToChars(profileNames, filename);

validateattributes(filename, {'char'}, {'row'}, 'exportProfile', 'filename', 2);

if ~iscell(profileNames)
    profileNames = {profileNames};
end

if ~iscellstr(profileNames) %#ok<ISCLSTR> we converted strings to chars
    error(message('parallel:settings:ExportProfileNamesMustBeString'));
end

try
    parallel.internal.pool.errorIfPoolThreadWorker(mfilename);
    profiles = cellfun(@(x) iGetProfilesFromName(x), profileNames, ...
        'UniformOutput', false);
    profiles = [profiles{:}];
    profiles.export(filename);
catch err
    throw(err);
end


%-------------------------------------------------
function profile = iGetProfilesFromName(name)
p = parallel.Settings;
% No point checking upfront if the name exists because
% we check afterwards that the profile isn't empty.
profile = p.findProfile('Name', name);
if isempty(profile) || ~parallel.internal.settings.isProfileVisible(name)
    % Unlikely to get in here unless the UI 
    % deletes the profile in between our call 
    % to hProfileExists and findProfile
    p.hThrowNonExistentProfile(name);
end



