function newCvd = addSubsystem(this, targetSubsys, cvd)
%

%   Copyright 2018-2019 The MathWorks, Inc.
    newCvd  = [];
    if ~valid(this) || ~valid(cvd)
        error(message('Slvnv:simcoverage:cvdata:InvalidCvData', 2));
    end

    
    targetCvId = findTargetCvId(this, targetSubsys, cvd);
    %no match
    if isempty(targetCvId)
        return;
    end
    %metricNames = {'decision'};
    %toMetricNames = {};
    [metricNames, toMetricNames] = cvi.MetricRegistry.getAllMetricNames;
    deleteIdx = contains(metricNames, {'sigrange', 'sigsize'});
    metricNames(deleteIdx == 1) = [];

    allMetricNames = [metricNames, toMetricNames];
    
    targetDescendantCvIds  = [targetCvId, cv('DecendentsOf', targetCvId)];
    targetIndexMap = cvdata.getMetricIndices(this, targetDescendantCvIds  , allMetricNames);
    
    sourceCvId = cv('get', cvd.rootID, '.topSlsf');
    sourceDescendantCvIds  = [sourceCvId, cv('DecendentsOf', sourceCvId)];
    sourceIndexMap = cvdata.getMetricIndices(cvd, sourceDescendantCvIds, allMetricNames);
    
    joinedAggregatedTestInfo = cvdata.joinAggregatedTestInfo(this, cvd);
    
    oldTraceOn = this.traceOn;
    this.traceOn = cvd.traceOn;
    
    [metricStruct, traceStruct] = cvdata.processSubsystemMetric(this.rootID, this, targetIndexMap, ...
                                                    cvd, sourceIndexMap, ...
                                                    joinedAggregatedTestInfo, ...
                                                    metricNames, toMetricNames, 'plus', false);
    [joinedAggregatedTestInfo, traceStruct] = cvdata.removeDuplicateTestTraces(joinedAggregatedTestInfo, traceStruct);
    newCvd  = cvdata;
    newCvd.createDerivedData(this, this, metricStruct, traceStruct);
    this.traceOn = oldTraceOn;
    cvdata.aggregateUniqueIds(newCvd, this, cvd);
    newCvd.aggregatedTestInfo = joinedAggregatedTestInfo;
end
%=============================
function targetCvId = findTargetCvId(this, targetSubsys, cvd)
    targetCvId  = [];
    subsysCvId  = cvprivate('find_block_cv_id', this.rootID, targetSubsys);
    if ischar(subsysCvId) %error - couldn't find
        return;
    end
    targetCheckSum = cv('get', subsysCvId, '.cvChecksum');
    sourceCheckSum = cv('get', cvd.rootId, '.checksum');
    if isequal(targetCheckSum, ...
               sourceCheckSum )
      targetCvId  = subsysCvId;
    end
    %TBD create new if not found
end