function Slist = ExpandedSortedlist(mdlh,expandLib, expandMdlRef)

if nargin < 3
    expandMdlRef = true; % Default is the slicer workflow
end

if nargin < 2
    expandLib = false;
end

Slist = [];

thisLvlSlist = get_param(mdlh,'SortedList');
thisLvlSlist = thisLvlSlist(ishandle(thisLvlSlist));

    for i = 1:length(thisLvlSlist)
        Slist(end+1) = thisLvlSlist(i); %#ok<*AGROW>get

        if strcmp(get_param(thisLvlSlist(i),'BlockType'),'SubSystem') && ...
           strcmp(get_param(thisLvlSlist(i),'TreatAsAtomicUnit'),'on') && ...
           ~slprivate('is_stateflow_based_block', thisLvlSlist(i))
       
          %We get the sorted list for library links only if these blocks
          %will be inlined in the sliced model. Without this check,
          %assigning priorities will raise a warning since we are modifying
          %the original library. We should still assign priority for the topmost
          %library subsystem.
          
           if(isempty(get_param(thisLvlSlist(i),'ReferenceBlock')) || expandLib)
               
               ChildTreeSlist = Analysis.ExpandedSortedlist(thisLvlSlist(i), ...
                                 expandLib, expandMdlRef);
               Slist = [Slist ChildTreeSlist];
               
           end
          
        elseif (strcmp(get_param(thisLvlSlist(i),'BlockType'),'ModelReference') && ...
               expandMdlRef)
        
            mdlRefh = get_param(get_param(thisLvlSlist(i),'ModelName'),'handle');
            ChildTreeSlist = Analysis.ExpandedSortedlist(mdlRefh,expandLib);
            Slist = [Slist ChildTreeSlist];
            
        end
        
    end

end
