function [coeffs, t, q, qd, qdd] = quintic_trajectory(q0, qf, v0, vf, a0_bc, af_bc, t0, tf, doPlot)
% QUINTIC_TRAJECTORY Solve and evaluate a 5th-order rest-to-rest trajectory.
%   [coeffs, t, q, qd, qdd] = quintic_trajectory() runs the default
%   coursework case: q(3)=0 -> q(8)=pi/2 with near-zero boundary velocities
%   and zero boundary accelerations.

    if nargin < 1 || isempty(q0),    q0 = 0; end
    if nargin < 2 || isempty(qf),    qf = pi / 2; end
    if nargin < 3 || isempty(v0),    v0 = 2e-9; end
    if nargin < 4 || isempty(vf),    vf = 5e-9; end
    if nargin < 5 || isempty(a0_bc), a0_bc = 0; end
    if nargin < 6 || isempty(af_bc), af_bc = 0; end
    if nargin < 7 || isempty(t0),    t0 = 3; end
    if nargin < 8 || isempty(tf),    tf = 8; end
    if nargin < 9 || isempty(doPlot), doPlot = (nargout == 0); end

    A = [
         t0^5,    t0^4,   t0^3,  t0^2, t0, 1;
       5*t0^4,  4*t0^3, 3*t0^2,  2*t0,  1, 0;
      20*t0^3, 12*t0^2,   6*t0,     2,  0, 0;
         tf^5,    tf^4,   tf^3,  tf^2, tf, 1;
       5*tf^4,  4*tf^3, 3*tf^2,  2*tf,  1, 0;
      20*tf^3, 12*tf^2,   6*tf,     2,  0, 0
    ];

    b = [q0; v0; a0_bc; qf; vf; af_bc];
    coeffs = A \ b;  % [a5; a4; a3; a2; a1; a0]

    t = linspace(t0, tf, 400);
    q   = polyval(coeffs, t);
    qd  = polyval(polyder(coeffs), t);
    qdd = polyval(polyder(polyder(coeffs)), t);

    if nargout == 0
        fprintf('Quintic polynomial coefficients [a5..a0]:\n');
        fprintf('  a5 = %.8g\n  a4 = %.8g\n  a3 = %.8g\n  a2 = %.8g\n  a1 = %.8g\n  a0 = %.8g\n\n', coeffs);
        fprintf('Boundary verification at t0 = %.2f s: q = %.6f rad, v = %.3e rad/s, a = %.3e rad/s^2\n', ...
            t0, q(1), qd(1), qdd(1));
        fprintf('Boundary verification at tf = %.2f s: q = %.6f rad, v = %.3e rad/s, a = %.3e rad/s^2\n', ...
            tf, q(end), qd(end), qdd(end));
    end

    if doPlot
        figure('Name', 'Quintic Trajectory Profile', 'NumberTitle', 'off');
        tiledlayout(3, 1, 'Padding', 'compact', 'TileSpacing', 'compact');
        nexttile; plot(t, q, 'LineWidth', 1.8); grid on; ylabel('q(t) [rad]'); title('Quintic Position');
        nexttile; plot(t, qd, 'LineWidth', 1.8); grid on; ylabel('v(t) [rad/s]'); title('Velocity');
        nexttile; plot(t, qdd, 'LineWidth', 1.8); grid on; ylabel('a(t) [rad/s^2]'); xlabel('Time t [s]'); title('Acceleration');
    end
end
