%% Question 1 - Cat & Mouse
% We simulate the cat's position $x$ in the Cat & Mouse system for
% $t\in[0, \frac{1}{v_m})$ by the ODE system:
%
% $$
% \left( \begin{array}{c} \frac{\mathrm{d}x_1}{\mathrm{d}t}\\\frac{\mathrm{d}x_2}{\mathrm{d}t} \end{array}\right)
% = \frac{v_c}{\left( (1-v_mt-x_1)^2 + x_2^2 \right)^{\frac12}}\left( \begin{array}{c} 1-v_mt-x_1\\-x_2\end{array}\right)
% $$
%
% where $v_m$ are $v_c$ are the mouse's and cat's velocities, respectively.
% The initial starting position of the mouse is given by $(1,0)^\top$ and
% the cat by $\tilde{x}$.

%% 1(a)
% We start with $\tilde{x}=(1, 1)^\top$, $v_m=1$ and $v_c=2$.

vm = 1;
vc = 2;
x0 = [1;1];
[~,x] = ode23(@(t,x) catmouse(t, x, vm, vc), [0, 1/vm], x0);

figure;
plot(x(:,1), x(:,2), x(1,1), x(1,2), 'o');
xlabel('x_1');
ylabel('x_2');

%%
% Now we consider $\tilde{x}=(0, 1)^\top$, $v_m=1$ and $v_c=2$.

vm = 1;
vc = 2;
x0 = [0;1];
[~,x] = ode23(@(t,x) catmouse(t, x, vm, vc), [0, 1/vm], x0);

figure;
plot(x(:,1), x(:,2), x(1,1), x(1,2), 'o');
xlabel('x_1');
ylabel('x_2');

%%
% Finally we consider $\tilde{x}=(1, 1)^\top$, $v_m=2$ and $v_c=2$.

vm = 2;
vc = 2;
x0 = [1;1];
[~,x] = ode23(@(t,x) catmouse(t, x, vm, vc), [0, 1/vm], x0);

figure;
plot(x(:,1), x(:,2), x(1,1), x(1,2), 'o');
xlabel('x_1');
ylabel('x_2');

%% 1(b)
% With $\tilde{x}=(1, 1)^\top$, $v_m=1$ and $v_c=2$ we zoom in around
% $x=0.33$. We note here that we get small oscillations, which is caused
% because the cat has caught the mouse.

vm = 1;
vc = 2;
x0 = [1;1];
[~,x] = ode23(@(t,x) catmouse(t, x, vm, vc), [0, 1/vm], x0);

figure;
plot(x(:,1), x(:,2), x(1,1), x(1,2), 'o');
xlim([.3 .35]);
ylim([-5e-6 5e-6]);
xlabel('x_1');
ylabel('x_2');

%% 1(c)
% We now use events to detect when the distance between the mouse ($y$)
% and the cat ($x$) is zero ($|x-y|=0$); i.e., the cat has caught the mouse
% and use it to terminate the simulation

vm = 1;
vc = 2;
x0 = [1;1];

options = odeset('Events',@(t, x) catmouseevents(t, x, vm));
[~,x,te,xe,ie] = ode23(@(t,x) catmouse(t, x, vm, vc), [0, 1/vm], x0, options);
if ~isempty(ie) && (ie == 1)
    disp('Cat caught the mouse:');
    fprintf('  At time:         %f\n', te);
    fprintf('  Cat''s position: (%f, %f)\n', xe(1), xe(2));
else
    disp('The mouse reached its hole');
end

figure;
plot(x(:,1), x(:,2), x(1,1), x(1,2), 'o');
xlabel('x_1');
ylabel('x_2');

%%
% Now we test a case when the mouse doesn't catch the mouse:
% $\tilde{x}=(1, 1)^\top$, $v_m=2$ and $v_c=2$


vm = 2;
vc = 2;
x0 = [1;1];
options = odeset('Events',@(t, x) catmouseevents(t, x, vm));
[~,x,te,xe,ie] = ode23(@(t,x) catmouse(t, x, vm, vc), [0, 1/vm], x0, options);
if ~isempty(ie) && (ie == 1)
    disp('Cat caught the mouse:');
    fprintf('  At time:         %f\n', te);
    fprintf('  Cat''s position: (%f, %f)\n', xe(1), xe(2));
else
    disp('The mouse reached its hole');
end

figure;
plot(x(:,1), x(:,2), x(1,1), x(1,2), 'o');
xlabel('x_1');
ylabel('x_2');
