function [t Y] = bar_puleni(F,G,Y0,tf,h,tol,cor)
  %input: F -- function handle, right hand side of diff. eqn
  %       G -- function handle, barrier
  %       Y0 -- initial condition at t = 0
  %       tf -- final time
  %       h -- stepsize
  %       tol -- error tolerance

i = 1;
t(i) = 0;
Y(i,:) = Y0;

%until tf is reached
while t(i) < tf
   %new approximate value w/adaptive stepsize
   f1 = F(t(i),Y(i,:));
   f2 = F(t(i) + (h/2),Y(i,:) + (h/2).*f1');
    
   A1 = Y(i,:) + h.*f1';
   A2 = Y(i,:) + (h/2).*f1' + (h/2).*f2';
    
   r = norm(A1-A2,inf);
    
    
    
   if r > tol
      h = 0.9*h*max(tol/r,0.3);
   else
      t(i+1,:) = t(i) + h;
      Y(i+1,:) = A2;
      h = 0.9*h*min(tol/r,2);
      
      
       %test if particle over barrier
       if G(t(i),Y(i,:))*G(t(i+1),Y(i+1,:)) < 0
         %remember last value before barrier was crossed
          t_s = t(i);
          Y_s = Y(i,:);
          hod = G(t_s,Y_s);
          h_new = h;%new stepsize is half of the old one
            while abs(G(t(i),Y(i,:))) > tol %while values above barrier
              %compute new values with half the previous stepsize
                h_new = h_new/2;
                t_1 = t(i) + h_new;
                Y_1 = Y(i,:) + h_new.*F(t(i),Y(i,:))';
                %test if new values over barrier, but within tolerance
                    if hod*G(t_1,Y_1) > 0
                      %if yes, accept them as new values
                      t(i+1) = t_1;
                      Y(i+1,:) = Y_1;
                      i = i +1;
                      
                    end       
                
            end
              %out of while, last point of touch accepted, now bounce
           Y(i,2) = -cor*Y(i,2);
           fprintf('dotek v t = %f\n',t(i))
            
      else
      %move forward outside of regin where we're close to barrier 
      i = i + 1;    
   end
  
end
    
    


end

%s while lze presahnout tf
N = length(t);
if t(N) ~= tf
  h = tf - t(N-1);
  t(N) = tf;
  Y(N,:) = Y(N-1,:) + h.*F(t(N-1),Y(N-1,:))';
  end   
     

end