function [t_n Y_n] = adapt(F,Y0,T,h0,tol)

	% F = @(t,X) [f_1(t,X(1),...,X(n));...;f_n(t,X(1),...,X(n))]; 
	% T = [t_0 tf]   row vector, t0 = starting time, tf = final time
	% Y0   row vector or a point, initial condition
	% h0   initial stepsize; default = 0.02
	% tol  error tolerance; default = 10^-3


%kontrola vstupu
if ~exist('h0','var') || isempty(h0)
    h0 = 0.02;
end

if ~exist('tol','var') || isempty(tol)
    tol = 0.001;
end

    

t0 = T(1);
b = T(2);

i = 1;
m = 0;

t = t0;
Y = Y0';%Y = column
h = h0;

t_n(i,1) = t;
Y_n(i,:) = Y;

count = 0;

    
    while(t < b) 
        f1 = F(t,Y);%column
        A1 = Y + h*f1;
        
        f2 = F(t + (h/2),Y + (h/2)*f1);%column        
        A2 = Y + (h/2)*f1 + (h/2)*f2;
        

        m = m+2;
        
        r = norm(A1-A2,inf);
        
        if(r > tol)
             h = 0.9*h*max(tol/r,0.3);
            count = count + 1;
        else
            i = i+1;
            t = t+h;           
            
            Y = A2;
            t_n(i,1) = t;
            Y_n(i,:) = Y';
            %after accepting Y_n, can increase stepsize 
            h = 0.9*h*min(tol/r,2);
            
         end

    end
    
%while can overstep tf
N = length(t_n);
if t_n(N) ~= T(2)
 t_n(N) = T(2);
 end
h = t_n(N) - t_n(N-1);

cor = Y_n(N-1,:) + h.*F(t_n(N-1),Y_n(N-1,:))';
Y_n(N,:) = cor;

  
    fprintf('pocet vyhodnoceni F %f\n',m)
    fprintf('pocet zamitnuti kroku %d\n',count)
end


	