function allDataDicts = getAllDataDictionariesInTheModelHierarchy(modelH)
% Brief: This API takes a model handle and returns all the data dictionaries
% referred by any model/library in the model hierarchy.

%   Copyright 2022 The MathWorks, Inc.

allDataDicts = [];

refMdls = find_mdlrefs(modelH, 'AllLevels', true,...
    'MatchFilter',@Simulink.match.internal.filterOutCodeInactiveVariantSubsystemChoices, ...
    'ReturnTopModelAsLastElement', false);

% We would want the top model to be processed first so that if it has all the
% entries, we would not have to attach any data dictionary attached to
% referenced models/libraries
refMdls = vertcat(getfullname(modelH), refMdls);

if ~isempty(refMdls)
    for i = 1:length(refMdls)
        refMdlH = get_param(refMdls{i},'Handle');
        refMdlDataDicts = slprivate('getAllDataDictionaries', refMdlH);
        refMdlHasDD = numel(refMdlDataDicts) > 0;
        if refMdlHasDD
            % Append data dictionary to running list, get_param on current
            % model is just to ensure that the top model DD remains in the
            % front if present. This would help optimize later in
            % createDDForReplacementMdl
            allDataDicts = [allDataDicts ...
                get_param(refMdls{i},'DataDictionary') refMdlDataDicts];
        end
    end

    % Pick up only the unique ones
    allDataDicts = unique(allDataDicts, 'stable');
end
end
