function [yesno, blkH] = isRootOfMdlref(refMdlToMdlBlk, bh)
% If bh maps to the root of reference model according to
% input map refMdlToMdlBlk, then this function returns true
% and a handle to the model reference in the original subsystem.
% Otherwise, this function returns [false, []].

%   Copyright 2016-2020 The MathWorks, Inc.
blkH = [];
yesno = false;
sysO = get(bh,'Object');

if isa(sysO,'Simulink.Port')
    return;
end
                
if ~isa(sysO, 'Simulink.BlockDiagram') && sysO.isSynthesized
    if isa(sysO, 'Simulink.ModelReference')
        parentH = sysO.getCompiledParent;
        if strcmp(get_param(parentH,'virtual'), 'on')
            %For model reference with virtual bus, the IR has
            %the synthesized model block and not it's parent
            %virtual subsystem. The true original block for the synthesized model
            %block resolves to itself. To get the correct model block in the
            %original model, we have to query the synthesized parent subsystem.
            
            parentO = sysO.getParent;
            blkH = parentO.getOriginalBlock;
            yesno = true;
        else
            % This case handles when synthesized model references are
            % created for function-call model blocks.
            % This case 
            blkH = parentH;
            yesno = true;
        end
    elseif isa(sysO, 'Simulink.SubSystem')
        p = sysO.getCompiledParent;
        if strcmp(get(p, 'Type'), 'block_diagram') && ...
                refMdlToMdlBlk.isKey(p)
            yesno = true;
            blkH = refMdlToMdlBlk(p);
            blkO = get_param(blkH, 'Object');
            if blkO.isSynthesized && ...
                    strcmp(blkO.getSyntReason,'SL_SYNT_BLK_REASON_FCNCALL_MODELREF') && ...
                    isa(blkO,'Simulink.ModelReference')
                blkH = blkO.getCompiledParent;
            end
        else
            yesno = false;
        end
    end
end
end
