function y = th_weighted_apply_filter_sosfilt(y, iphase, ~, a, b)
% th_weighted_apply_filter_sosfilt
% sosfilt equivalent of th_weighted_apply_filter, robust to padded rows/cols.
%
% y = th_weighted_apply_filter_sosfilt(y, iphase, [], a, b)

    % Preserve original shape
    wasRow = isrow(y);
    y = y(:);

    % Optional reversal (same as original)
    if iphase == 1
        y = flipud(y);
    end

    % Use only first 3 columns of b and columns 2:3 of a (as in original)
    b3 = b(:, 1:3);
    a23 = a(:, 2:3);

    % Keep only "real" sections (ignore padded all-zero rows)
    % A section is valid if either numerator or denominator (a1/a2) has any nonzero
    isSection = any(abs(b3) > 0, 2) | any(abs(a23) > 0, 2);

    b3  = b3(isSection, :);
    a23 = a23(isSection, :);

    % Safety check: need at least one section
    if isempty(b3)
        error('No valid SOS sections found in a/b.');
    end

    % Build SOS matrix: [b0 b1 b2 a0 a1 a2], with a0 = 1
    sos = [b3, ones(size(b3,1),1), a23];

    % Apply cascade
    y = sosfilt(sos, y);

    % Restore original shape
    if wasRow
        y = y.';
    end
end
