function sort(this,hRegistrationSet)
%sort Sort configurations by registration order and dependencies.
%   Sort configurations by registration type-order and extension order,
%   provided by extensions during registration.  Also sort according to
%   dependency, issuing messages if there are failures.

%   Copyright 2014-2020 The MathWorks, Inc.

sortedTypeNames = hRegistrationSet.SortedTypeNames;
% Get all Config separated according to sorted type names
%
% c{indx} contains a vector of Register of the same type name
% typeNames{indx} indicates the type name of the group
N = numel( sortedTypeNames );
c = cell( 1, N );
hConfigs = this.Children;
if isempty(hConfigs)
    % Nothing to sort
    return;
end
allTypes = { hConfigs.Type };
for indx = 1:N
    % Reorder extensions within each type, according to
    % individual extension order, then re-connect extensions in
    % new order
    ci = hConfigs( strcmp( allTypes, sortedTypeNames{ indx } ) );  % get all Config's in next type-group
    % get vector of registration order info
    % Find registration objects corresponding to each config object
    if ~isempty( ci )
        hRegisters = [ ci.Registration ];
        % Get order info
        o = [ hRegisters.Order ];
        % Sort/reorder configs:
        [~,ext_sort_order] = sort( o );
        ci = ci( ext_sort_order );  % reorder Config's in this type-group
        c{ indx } = ci( : )';
    end
end
c = [ c{ : } ];
% xxx Make sure that extensions that rely on other extensions are at the
% end, so that when we enable them, their dependent extensions are enabled.
% This algorithm needs some work, it won't be reliable for multiple
% dependencies, or "dependency chains".
indx = 1;
nMoved = 0;
while indx<length( c ) - nMoved
    hRegister = c( indx ).Registration;
    if isempty( hRegister.Depends )
        % If there are no dependencies, move to the next config.
        indx = indx + 1;
    else
        % If we find a dependency, just move it to the end, so it gets
        % added last.
        c = [ c( 1:indx - 1 ), c( indx + 1:end ), c( indx ) ];
        nMoved = nMoved + 1;
    end
end
this.Children = c;
end
