function [cumPartC, C, szC] = convTrimResult(cumPartC, C, dim, szA, szB, szC, isSame, isValid, ABswapped)
% Helper to trim the result based on the shape input.  It truncates the
% undistributed dimensions of the partial result, changes the size of the
% final result and changes the cumulative partition of the final result.

% Copyright 2016-2022 The MathWorks, Inc.

if ABswapped  % Swap szA and szB back before trimming.
    [szA, szB] = deal(szB, szA);
end
szA = [szA ones(1, numel(szC) - numel(szA))];
szB = [szB ones(1, numel(szC) - numel(szB))];
index = cell(1,ndims(C));

if isValid
    for ii = 1:numel(szC)
        if ii == dim
            index{ii} = ':';
        else
            index{ii} = szB(ii):szC(ii)+1-szB(ii);
        end
        if isempty(index{ii})
            szC(ii) = 0;
        else
            szC(ii) = max(szC(ii) - 2*(szB(ii)-1), 0);
        end
    end
    C = subsref(C,struct('type','()','subs',{index}));
    cumPartC = max(cumPartC, szB(dim)-1);
    cumPartC = min(cumPartC, szC(dim)-1 + szB(dim));
    
elseif isSame
    % Match size of A
    szC = szA;
    offset = floor(szB/2);

    for ii = 1:ndims(C)
        if ii == dim
            index{ii} = ':';
        else
            index{ii} = offset(ii) + (1:szA(ii));
        end
    end
    C = subsref(C,struct('type','()','subs',{index}));
    cumPartC = max(cumPartC, offset(dim));
    cumPartC = min(cumPartC, offset(dim)+szA(dim));

else
    % Full, so nothing to trim
end
end