function odeEventDemo(tStop)
  if nargin <1
    tStop=20;
  end

  y0=0;

  [t,y]=integrateWithEvent(@theOde, 0, tStop, y0, @myEvent, @myOnEvent);

  plot(t,y);

  function [t,y]=integrateWithEvent(fn, tstart, tstop, y0, event, onEvent)
    t=[];
    y=[];
    tStart=tstart;
    while true
      [tPrime, yPrime]=ode45(fn, [tStart, tstop], y0, odeset('Events',event));
      t=[t;tPrime];
      y=[y;yPrime];
      num=length(tPrime);
      y0=yPrime(num,:);
      if (tPrime(num)>=tstop)
        break;
      else
        tStart=tPrime(num);
        y0=onEvent(tStart,y0);
      end
    end
  end

  % resets y to zero whenever the event occurs
  function result=myOnEvent(t,y)
    result=0;
  end

  function dy=theOde(t,y)
    dy=y+1;
  end

  function [value,isterminal,direction]=myEvent(t,y)
    value=y-4;
    direction=1;
    isterminal=1;
  end
end