%
% apply_filter_order_sosfilt.m  (sosfilt version, preserves original shape)
%
%    ver 1.0  by Tom Irvine
%
% Equivalent to apply_filter_order.m (revised/corrected) but uses sosfilt.
%
function y = apply_filter_order_sosfilt(y, iphase, ~, a, b, L_order)

    disp(' ')
    disp(' apply filter ')

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

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

    % Determine number of stages from order (matches your logic)
    % Always stages 1 & 2, add stage 3 if >=6, add stage 4 if ==8
    if L_order == 8
        nStages = 4;
    elseif L_order >= 6
        nStages = 3;
    else
        nStages = 2;
    end

    % Basic input checks (only what we use)
    if size(b,2) < 3
        error('b must have at least 3 columns (b(:,1:3)).');
    end
    if size(a,2) < 3
        error('a must have at least 3 columns (a(:,2:3)).');
    end
    if size(b,1) < nStages || size(a,1) < nStages
        error('a and b must have at least %d rows for L_order=%d.', nStages, L_order);
    end

    % Build SOS matrix: each row is [b0 b1 b2 a0 a1 a2], with a0 = 1
    % Original per-stage:
    %   forward = b(ik,1:3)
    %   back    = [1 a(ik,2) a(ik,3)]
    b3  = b(1:nStages, 1:3);
    a23 = a(1:nStages, 2:3);
    sos = [b3, ones(nStages,1), a23];

    % Stage messages (to mimic original prints)
    disp('  stage 1');
    disp('  stage 2');
    if nStages >= 3, disp('  stage 3'); end
    if nStages >= 4, disp('  stage 4'); end

    % Apply cascade in one call
    y = sosfilt(sos, y);

    disp(' end apply filter');

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

end
