function this_Trace = getTraceContributionForSide(this_cvdata, this_TraceData, this_OutcomeExecuted, other_OutcomeExecuted, ...
                                                     joinedAggregatedTestInfo, needTraceIdRemap)
%
                                           
%   Copyright 2019 The MathWorks, Inc.

    try    
        this_TraceTemp = [];
        if ~isempty(this_TraceData)
            this_TraceTemp = this_TraceData;
        end

        if (this_OutcomeExecuted)
            % This side executed, so it should contribute to trace.
            if isempty(this_TraceTemp)
                % Get trace id for this run.
                this_Trace = cvdata.getInternalTraceId(this_cvdata.uniqueId, joinedAggregatedTestInfo);
            else
                % Use existing trace ids, but remap as necessary.
                this_Trace = resolveTraceId(this_TraceTemp, this_cvdata, joinedAggregatedTestInfo, needTraceIdRemap);
            end
        elseif (~other_OutcomeExecuted) && ~isempty(this_TraceTemp)
            % Not executed on either side, but has (incidental) trace.
            % Use existing trace ids, but remap as necessary.
            this_Trace = resolveTraceId(this_TraceTemp, this_cvdata, joinedAggregatedTestInfo, needTraceIdRemap);
        else
            % Not executed on this side, but is executed on other side.
            % This side won't contribute trace.
            % (Will throw away incidental trace, if applicable.)
            this_Trace = [];
        end
    catch MEx
        rethrow(MEx);
    end

end

function traceRemapped = resolveTraceId(trace, cvd, joinedAggregatedTestInfo, needTraceIdRemap)
    if needTraceIdRemap
        traceRemapped  = remapTraceIds(trace, cvd, joinedAggregatedTestInfo);
    else
        traceRemapped = trace;
    end
end

function traceIds = remapTraceIds(traceIds, cvd, joinedAggregatedTestInfo)
    for idx = 1 : numel(traceIds)
        uniqueId = cvdata.getUniqueIdFromTraceId(cvd.aggregatedTestInfo, traceIds(idx));
        traceIds(idx) = cvdata.getInternalTraceId(uniqueId, joinedAggregatedTestInfo); 
    end
end
    