function [t,x] = am2(field, t0, T, x0, h)
%AM2 Implements the Adams-Moulton two-step ODE solver
%
% Parameters:
%  field  -- Right hand side function of ODE system: x'=f(t,x)
%  t0     -- Initial time
%  T      -- End time (T > t0)
%  x0     -- Initial value
%  h      -- Size of time step (h <= T-t0)
%
% Outputs:
%  t  -- [t0; t-0+h, t0+2*h; ...; t0+i*h; ...]
%  x  -- Column vector containing numerical solution at each time step

tol = 0.05;
m = 2;
n = ceil((T-t0)/h);

t = t0+h*(0:n).';
x = ones(n+1,length(x0));
[t(1:m), x(1:m,:)] = rk_classical(field, t0, t0+(m-1)*h, x0, h);

f0 = feval(field, t(m), x(m,:)');
f1 = feval(field, t(m-1), x(m-1,:).');
for i=m:n
    f_old = feval(field, t(i)+h, x(i,:).');
    x(i+1,:) = x(i,:).' + h*(5*f_old+8*f0-f1)/12;
    f_new = feval(field, t(i)+h, x(i+1,:).');
    while norm(f_old-f_new, 'inf') >= tol
        f_old = f_new;
        x(i+1,:) = x(i,:).' + h*(5*f_old+8*f0-f1)/12;
        f_new = feval(field, t(i)+h, x(i+1,:).');
    end
    f1 = f0;
    f0 = f_new;
end