function [value,isterminal,direction]=events(t,y)
% Refer to 5-48,5-49,5-50, "Matlab, Mathematic. The language of Technical 
% Computing". The MathWorks. 2004. Matlab7.
%
% The system is defined as follows:
% (1) y_1'=y_3
% (2) y_2'=y_4
% (3) y_3'=2(y_4)+(y_1)-[(µ*((y_1)+µ)/(r_1)^3]-[(µ(y_1)+µ*)/(r_2)^3]
% (4) y_4'=-2(y_3)+(y_2)-[µ*(y_2)/(r_1)^3]-[(µ(y_2)/(r_2)^3]
% with 
% µ=1/82.45
% µ*=1-µ
% r1=[(y_1)+µ)^2+(y_2)^2]^(1/2) 
% r2=[(y_1)-µ*)^2+(y_2)^2]^(1/2)
%
% Locate the time when the object returns closest to the
% initial point y0 and starts to move away, and stop integration.
% Also locate the time when the object is farthest from the
% initial point y0 and starts to move closer. 
% The current distance of the body is
% DSQ = (y(1)-y0(1))^2+(y(2)-y0(2))^2
%     = <y(1:2)-y0,y(1:2)-y0>
% A local minimum of DSQ occurs when d/dt DSQ crosses zero 
% heading in the positive direction. We can compute d(DSQ)/dt as
% d(DSQ)/dt = 2*(y(1:2)-y0)'*dy(1:2)/dt=2*(y(1:2)-y0)'*dy(3:4);
% 
y0 = [1.2;0];
dDSQdt = 2*((y(1:2)-y0)'*y(3:4));
value = [dDSQdt; dDSQdt];
isterminal = [1; 0];
direction = [1; -1];

% The MathWorks, Matlab7. Copyright (c).
