function save(h, viewsToSave, fileName)
% save
%
% Save ModelExplorer views.
%


% Copyright 2009-2011 The MathWorks, Inc.

if nargin > 2
    fileName = convertStringsToChars(fileName);
end

if ~h.Serialize
    % If not to serialize, return.
    return;
end

views = [];

switch nargin
    case 2
        % Find all the views.
        views = find(h, '-isa', 'DAStudio.MEView');
        fileName = h.getFileName();
    case 3
        views = viewsToSave;
        fileName = fileName;       
end

allDomains = h.Domains;
% Start filling attributes.
for i = 1:length(views)
    meViews(i).Name = views(i).Name; 
    meViews(i).Domain = '';
    meViews(i).Description = views(i).Description;
    meViews(i).InternalName = '';
    meViews(i).GroupName = '';
    meViews(i).SortName = '';
    meViews(i).SortOrder = '';
    % fill domain name for this view if any.
	for j = 1:length(allDomains)
		domainActView = allDomains(j).getActiveView();
		
		if ~isempty(domainActView) && strcmp(domainActView.Name, views(i).Name)
			meViews(i).Domain = allDomains(j).Name;
        end
    end
    meViews(i).Properties = [];
    if ~isempty(views(i).Properties)
        meViews(i).Properties = find(views(i).Properties, 'isVisible', true);
        meViews(i).GroupName = views(i).GroupName;
        meViews(i).SortName = views(i).SortName;
        meViews(i).SortOrder = views(i).SortOrder;        
    end
    if ~isempty(views(i).InternalName)
        meViews(i).InternalName = views(i).InternalName;
    end
    if isprop(views(i),'FilterTypes')
        if ~isempty(views(i).FilterTypes)
            meViews(i).FilterTypes = views(i).FilterTypes;
        end
    end
end

try
    % Save as meViews.
    save(fileName, 'meViews');
    % These are preferences if filename is same.
    if strcmp(h.getFileName, fileName)
        % Save release version.
        viewsVersion = h.MATLABVersion;
        save(h.getFileName(), 'viewsVersion', '-append');
        % Save active view.
        if ~isempty(h.ActiveView)
            activeView = h.ActiveView.Name;
        else
            if ~isempty(views)
                activeView = views(1).Name;
            end
        end
        save(h.getFileName(), 'activeView', '-append');
        % Save suggestions settings.
        suggestionMode = h.SuggestionMode;
        save(h.getFileName(), 'suggestionMode', '-append');
    end
catch ME    
    MSLDiagnostic('modelexplorer:DAS:ErrorWritingViewDefinitions').reportAsWarning;
end
