function [dx, out] = nonlinear_bicycle_rhs(t, x, p)
%NONLINEAR_BICYCLE_RHS Planar reference equations for forward motion.
% This is an explanatory model core, not a reconstruction of a completed
% ADAMS comparison. No measured or original tyre-spline data are supplied.
%
% x = [u; v; r; X; Y; psi], in m/s, m/s, rad/s, m, m, rad.
% Body axes: x forward, y left, positive yaw counter-clockwise.
% Required parameters:
%   p.mass, p.Iz, p.a, p.b: kg, kg*m^2, m, m.
%   p.steer(t): front steering angle in radians.
%   p.frontTyre(alpha), p.rearTyre(alpha): signed equivalent-wheel forces
%       in N, with slip input in radians. Each force is used once per axle.
%   p.drive(t,x): longitudinal drive force at the CG in N.
%   p.drag(u): opposing drag magnitude in N for forward travel.
%   p.minSpeed: positive lower operating-speed limit in m/s.
%
% Supply and verify these functions before integrating with ode45.
% For a degree-based ADAMS spline, convert slip with rad2deg inside each
% tyre function. Match its normalization, interpolation and endpoint rules.
% MATLAB makima is not automatically identical to ADAMS AKISPL.
% No roll, pitch, combined slip, load dependence or tyre relaxation state.

x = x(:);
assert(numel(x) == 6 && all(isfinite(x)), 'State must contain six finite values.');
assert(p.mass > 0 && p.Iz > 0 && p.a > 0 && p.b > 0 && p.minSpeed > 0, ...
    'Mass, inertia, axle distances and minimum speed must be positive.');
u = x(1); v = x(2); r = x(3); psi = x(6);
assert(u > p.minSpeed, 'Outside the forward-running model range.');
delta = p.steer(t);
alphaF = delta - atan2(v + p.a*r, u);
alphaR = -atan2(v - p.b*r, u);
Fyf = p.frontTyre(alphaF);
Fyr = p.rearTyre(alphaR);
Fdrive = p.drive(t,x);
Fdrag = p.drag(u);
assert(all(isfinite([delta alphaF alphaR Fyf Fyr Fdrive Fdrag])), ...
    'Steering or force function returned a non-finite value.');

Fx = Fdrive - Fdrag - Fyf*sin(delta);
Fy = Fyf*cos(delta) + Fyr;
Mz = p.a*Fyf*cos(delta) - p.b*Fyr;
dx = [Fx/p.mass + r*v;
      Fy/p.mass - u*r;
      Mz/p.Iz;
      u*cos(psi) - v*sin(psi);
      u*sin(psi) + v*cos(psi);
      r];
out = struct('steering_rad',delta,'front_slip_rad',alphaF, ...
    'rear_slip_rad',alphaR,'front_force_N',Fyf,'rear_force_N',Fyr, ...
    'lateral_acceleration_m_per_s2',Fy/p.mass,'yaw_moment_N_m',Mz);
end
