function reaggregateFromTrace(this, metricName, isTOMetric, traceMask)
% Reaggregate metricData using traces (applying trace mask)

%   Copyright 2019 The MathWorks, Inc.

    metricStruct = this.metrics;
    isSigrange = strcmpi(metricName,'sigrange') || strcmpi(metricName,'sigsize');
    
    % Generate masked trace table.
    if isTOMetric
        maskedTrace = this.trace.testobjectives.(metricName);
    else
        maskedTrace = this.trace.(metricName);
    end
    
    if ~isempty(traceMask)
        if isSigrange
            maskedTrace(~traceMask) = NaN;
        else
            maskedTrace = full(maskedTrace.*traceMask);
        end
    end
    
    % Re-aggregate results in masked trace table for this metric.
    metricData =  processMetric(this.rootId, metricName, maskedTrace);
  
    % Perform further processing on metric data based on metric type.
    if isTOMetric
        tmpMtricStruct = [];
        if ~isempty(metricData)
            metricenumValue = cvi.MetricRegistry.getEnum(metricName);    
            metricdataId = cv('new', 'metricdata', '.metricName', metricName, '.metricenumValue',metricenumValue);
            cv('set',metricdataId ,'.data.rawdata', metricData,'.size', numel(metricData)); 
            metricData = cv('ProcessTOData',this.rootId, metricdataId);
            cv('delete',metricdataId ); 
        end
        tmpMtricStruct.(metricName) = metricData;
        metricStruct.testobjectives = tmpMtricStruct;

    else % ~isTOMetric
        if ~isempty(metricData) && ~isSigrange 
            metricEnumVal = cvi.MetricRegistry.getEnum(metricName);     
            metricData = cv('ProcessData',this.rootId, metricEnumVal, metricData);
        end
        metricStruct.(metricName) = metricData;
    end
    
    % Write back the updated metric data to this cvdata object.
    this.setMetricData(metricStruct);
end

%%
%=================================
function  u = processMetric(rootId, metric, maskedTrace)
    opFcn = @(x)(sum(x,2));
    u = cvdata.processMetric(rootId, metric, maskedTrace, opFcn, '+');
end
