function [supportedrefs, supportedrefblocks] = getMdlReferences(mdl, allLevel, closeunopenedmodels, supportedSimModes)
%

% Copyright 2007-2018 The MathWorks, Inc.


% Parse inputs
if nargin < 2
    allLevel = false;
end
if nargin < 3
    closeunopenedmodels = false;
end
if nargin < 4
    supportedSimModes = {'Normal'};
end

% Find all the models that are open
open_diagrams = find_system('type','block_diagram');

% Determine if the top model is loaded
if ~any(strcmp(mdl,open_diagrams))
    load_system(mdl);
end


% Start with the top model and recurse to find all the normal mode model
% references.

supportedrefs = {};
supportedrefblocks = {};
toclose = {};

% Find the normal mode model references
NestedFindMdlBlks(get_param(mdl, 'Name'))

    function NestedFindMdlBlks(mdl)
        mdlblks = find_system(mdl,'FollowLinks','on',...
            'LookUnderMasks','all',...
            'BlockType','ModelReference');
        
        if isempty(mdlblks)
            mdl_supportedlblks = {};
        else
            ind_supported = ismember(get_param(mdlblks,'SimulationMode'),supportedSimModes);
            ind_protected = strcmpi(get_param(mdlblks,'ProtectedModel'),'on'); 
            mdl_supportedlblks = mdlblks(ind_supported & ~ind_protected);
        end
        supportedrefblocks = [supportedrefblocks; mdl_supportedlblks];
        mdl_supportedrefs = get_param(mdl_supportedlblks,'ModelName');
        supportedrefs = unique([supportedrefs;mdl_supportedrefs]);
       
        if allLevel 
            for ct = 1:numel(mdl_supportedrefs)  
                mn = mdl_supportedrefs{ct};
                if ~any(strcmp(mn,open_diagrams)) 
                    load_system(mn);
                    toclose{end + 1} = mn;  %#ok<AGROW>
                end
                NestedFindMdlBlks(mn);
            end
        end
    end



% Close the opened models if requested
if closeunopenedmodels
    for ct_outer = 1:length(toclose)
        close_system(toclose{ct_outer});
    end
end

end