%%
clear all; clc; format compact;

%% Version (a) ... simple filling
clc;
[t, V] = ode45(@tim_tank_a, [0,30],0);
plot(t,V, 'o','Markersize',3)
final_vol = V(length(V))
% !!!!! overshoots due to poor RelTol
%% ... fixing the problem of overfilling
clc;
odeopts = odeset('RelTol', 1e-9)
spacing = 1; % this is the frequency of reporting, not stepsize
[t, V] = ode45(@tim_tank_a, [0:spacing:30],0, odeopts);
plot(t,V, 'o','Markersize',3)
final_vol = V(length(V))

%% Version (b) ... filling and emptying with cessation of inflow
clc;
global neverbeenfilled
neverbeenfilled = true;

spacing = 0.1;
tfinal = 100; % end of simulation
h_init = 1; % initial condition (h-variable)
odeopts = odeset('RelTol', 1e-9);
[t, V] = ode45(@tim_tank_b, [0:spacing:tfinal],h_init, odeopts);
plot(t,V)

%% Version (c) ... Using "events" to make changes during the integration
% In this version, we employ two (2) tanks. Tank 1 still has a hole
% and receives the inflow. Once full, the inflow is directed to
% Tank 2. The simulation is halted when Tank 2 becomes full.
% Tank 2 is full when V2=10 since Tank 2 has A2=2 and H2=5.

clc;
global neverbeenfilled
neverbeenfilled = true;

% we employ an event to detect the full tank condition
odeopts = odeset('RelTol', 1e-9, 'Events', @tank2_full);
ics = [0;0]; % initial conditions
time_vec = [0:0.01:100]; % independent variable (time)
[t, V, te, Ve, which] = ode45(@tim_tank_c, time_vec, ics, odeopts);
plot(t, V(:,1), t, V(:,2))