function newCvd = getAggregatedSubset(this, traceIdxs)
% Return re-aggregated cvdata using a subset of the existing traces.
%

%   Copyright 2020 The MathWorks, Inc.

    % Validity checks
    if isempty(this.trace) || (max(traceIdxs) > length(this.aggregatedTestInfo))
        newCvd = this;
        return;
    end

    % Get enabled metrics
    [metricNames, toMetricNames] = getEnabledMetricNames(this);
    deleteIdx = contains(metricNames, {'sigrange', 'sigsize'}); % Unsupported metrics
    metricNames(deleteIdx == 1) = [];                           
    allMetricNames = [metricNames, toMetricNames];
    isTOmetric = [zeros(1,numel(metricNames)), ones(1,numel(toMetricNames))];
    
    % Create subset trace structure
    traceStruct = [];
    for metricIdx = 1:length(allMetricNames)
        metricName = allMetricNames{metricIdx};
        
        if isTOmetric(metricIdx)
            tmpTrace = this.trace.testobjectives.(metricName);
            traceStruct.testobjectives.(metricName) = tmpTrace(:,traceIdxs);
        else
            tmpTrace = this.trace.(metricName);
            traceStruct.(metricName) = tmpTrace(:,traceIdxs);
        end
          
    end
    
    % Create new cvdata object with trace and ati subsets.
    tmpCvd = cvdata;
    tmpCvd.createDerivedData(this,  this, this.metrics, traceStruct);
    tmpCvd.aggregatedTestInfo = this.aggregatedTestInfo(traceIdxs);
    
    
    % Reaggregate metrics
    thisTraceMask = this.getTraceMask;
    for metricIdx = 1:length(allMetricNames)
        metricName = allMetricNames{metricIdx};

        % Subset the traceMask (used for scope to reqs), if available.
        locTraceMask = [];
        if ~isempty(thisTraceMask) && isfield(thisTraceMask, metricName)
            tmpTraceMask = thisTraceMask.(metricName);
            tmpCvd.traceMask.(metricName) = tmpTraceMask(:,traceIdxs);
            if tmpCvd.scopeDataToReqs
                % If data is scoped to requirements, then also apply the
                % updated traceMask while reaggregating.
                locTraceMask = tmpCvd.traceMask.(metricName);
            end
        end

        tmpCvd.reaggregateFromTrace(metricName, isTOmetric(metricIdx), locTraceMask)
    end
    
    newCvd = commitdd(tmpCvd);
end


