function [ tv, uv ] = heun( fun, y0, t0, tf, Nh )
% HEUN Heun method for the scalar ODE in the form
% y'(t) = f(t,y(t)),  t \in (t0,tf)
% y(0) = y_0
%
%  [ tv, uv ] = heun( fun, y0, t0, tf, Nh )
%  Inputs: fun    = function handle for f(t,y), fun = @(t,y) ...
%          y0     = initial value
%          t0     = initial time
%          tf     = final time
%          Nh     = number of time subintervals
%  Output: tv     = vector of time steps (1 x (Nh+1))
%          uv     = vector of approximate solution at times tv
%

tv = linspace( t0, tf, Nh + 1 );
h = ( tf - t0 ) / Nh;

uv = zeros( 1, Nh + 1 );
uv( 1 ) = y0;

for n = 1 : Nh
    u_star = uv( n ) + h * fun( tv( n ), uv( n ) ); 
    uv( n + 1 ) = uv( n ) + h / 2 * ( fun( tv( n ), uv( n ) ) + ...
                                      fun( tv( n + 1 ), u_star ) ); 
end

return