function activeModel = getActiveModel(obj)
% Return the name of the active model (in order to account for test
% harnesses).  Check the following models to see which is active:
%   
%  (1) Harness model specified in current cumulative cvdata
%  (2) Owner model specified in current cumulative cvdata
%  (3) Analyzed model specified in current cumulative cvdata
%  (4) topModelName specified for this ResultsExplorer object.

% Copyright 2020 The MathWorks, Inc.
try
    ccdRootNode = obj.root.activeTree.root;
    if ~isempty(ccdRootNode) && ...
       ~isempty(ccdRootNode.data) && ...
       ~isempty(ccdRootNode.data.cvd)
   
        cvd = ccdRootNode.data.cvd;
        if isa(cvd, 'cv.cvdatagroup')
            allCvd = cvd.getAll();
            cvd = allCvd{1};
        end
        
        try
            modelinfo = cvd.modelinfo;
        catch
            % cvdata no longer valid.
            modelinfo = [];
        end
        
        if ~isempty(modelinfo)
            activeModel = modelinfo.harnessModel;
            if isActive(activeModel)
                return;
            end
            activeModel = modelinfo.ownerModel;
            if isActive(activeModel)
                return;
            end
            activeModel = modelinfo.analyzedModel;
            if isActive(activeModel)
                return;
            end
        end
    end
    
    activeModel = obj.topModelName;
    if isActive(activeModel)
        return
    end
 
    activeModel = [];
catch SlCovMExc
    rethrow(SlCovMExc);
end
end

function result = isActive(model)
% Check if model is "active".
% Active model will be loaded and have valid CoverageId.

    result = false;
    if ~isvarname(model) || ~bdIsLoaded(model)
        return
    end

    modelcovId = get_param(model, 'CoverageId');
    if (modelcovId == 0) || ~cv('ishandle', modelcovId)
        return
    end
    result = true;
end