function results = cubic_vs_quintic_benchmark(q0, qf, t0, tf, doPlot)
% CUBIC_VS_QUINTIC_BENCHMARK Compare 3rd-order (cubic) vs 5th-order (quintic)
% rest-to-rest joint trajectories on peak velocity, peak acceleration, and jerk.

    if nargin < 1 || isempty(q0), q0 = 0; end
    if nargin < 2 || isempty(qf), qf = pi / 2; end
    if nargin < 3 || isempty(t0), t0 = 3; end
    if nargin < 4 || isempty(tf), tf = 8; end
    if nargin < 5 || isempty(doPlot), doPlot = (nargout == 0); end

    t = linspace(t0, tf, 400);

    % Cubic: q(t0)=q0, v(t0)=0, q(tf)=qf, v(tf)=0
    Ac = [
        t0^3,   t0^2, t0, 1;
      3*t0^2, 2*t0,    1, 0;
        tf^3,   tf^2, tf, 1;
      3*tf^2, 2*tf,    1, 0
    ];
    bc = [q0; 0; qf; 0];
    cc = Ac \ bc;
    qc   = polyval(cc, t);
    vc   = polyval(polyder(cc), t);
    ac   = polyval(polyder(polyder(cc)), t);
    jc   = polyval(polyder(polyder(polyder(cc))), t);

    % Quintic via quintic_trajectory
    [~, ~, qq, vq, aq] = quintic_trajectory(q0, qf, 0, 0, 0, 0, t0, tf, false);
    jq = gradient(aq, t(2) - t(1));

    results.cubic_peak_vel  = max(abs(vc));
    results.cubic_peak_acc  = max(abs(ac));
    results.cubic_peak_jerk = max(abs(jc));
    results.quintic_peak_vel  = max(abs(vq));
    results.quintic_peak_acc  = max(abs(aq));
    results.quintic_peak_jerk = max(abs(jq));

    if nargout == 0
        fprintf('=== Cubic vs Quintic Benchmark (q: %.2f -> %.2f rad, t: [%.1f, %.1f] s) ===\n', q0, qf, t0, tf);
        fprintf('Cubic   | peak |v|=%.4f rad/s | peak |a|=%.4f rad/s^2 | peak |j|=%.4f rad/s^3\n', ...
            results.cubic_peak_vel, results.cubic_peak_acc, results.cubic_peak_jerk);
        fprintf('Quintic | peak |v|=%.4f rad/s | peak |a|=%.4f rad/s^2 | peak |j|=%.4f rad/s^3\n', ...
            results.quintic_peak_vel, results.quintic_peak_acc, results.quintic_peak_jerk);
    end

    if doPlot
        figure('Name', 'Cubic vs Quintic Trajectory Comparison', 'NumberTitle', 'off');
        tiledlayout(3, 1, 'Padding', 'compact', 'TileSpacing', 'compact');
        nexttile; plot(t, qc, '--', t, qq, '-', 'LineWidth', 1.8); grid on; ylabel('q(t) [rad]'); legend('Cubic', 'Quintic');
        nexttile; plot(t, vc, '--', t, vq, '-', 'LineWidth', 1.8); grid on; ylabel('v(t) [rad/s]');
        nexttile; plot(t, ac, '--', t, aq, '-', 'LineWidth', 1.8); grid on; ylabel('a(t) [rad/s^2]'); xlabel('t [s]');
    end
end
