function [sys,x0,str,ts] = VisualTank(t,x,u,flag)
% S-function graphique pour modéliser et représenter une chaine de
% réservoirs d'eau.
switch flag,
  case 0
    [sys,x0,str,ts] = mdlInitializeSizes(t); % Initialization
  case 1
    sys = mdlDerivatives(t,x,u); % Update discrete states
  case 3
    sys = mdlOutputs(t,x,u); % Calculate outputs
  case 9
    sys = mdlTerminate(t,x,u); 
  case {1, 2, 4} % Unused flags
    sys = [];
  otherwise
    error(['unhandled flag = ',num2str(flag)]); % Error handling
end
% End of dsfunc.
%==============================================================
% Initialization
%==============================================================
function [sys,x0,str,ts] = mdlInitializeSizes(t)
% Call simsizes for a sizes structure, fill it in, and convert it 
% to a sizes array.
sizes = simsizes;
sizes.NumContStates  = 3;
sizes.NumDiscStates  = 0;
sizes.NumOutputs     = 3;
sizes.NumInputs      = 1;
sizes.DirFeedthrough = 0; % Matrix D is empty.
sizes.NumSampleTimes = 1;
sys = simsizes(sizes);
x0  = [1;0;0];       % Initialize the states.
global h T S Sc g
close all
h=visualbac([],5*x0);
R = 0.15; % m, rayon du fond du bac
S = pi*R^2; % m2
g=9.81; % m/s2
r= 0.005; % m, rayon de la section contractée du trou 
Sc = pi*r^2; % m2
g=1/2;S=1;Sc=1;
T=0;
str = [];            % Set str to an empty matrix.
ts  = [0 0];       % sample time: [period, offset]
% End of mdlInitializeSizes.
%==============================================================
% Update the discrete states
%==============================================================
function sys = mdlDerivatives(t,x,u)
global S Sc g
if x(3)>0,H2=x(3);else,H2=0;end,
if x(2)>0,H1=x(2);else,H1=0;end,
if x(1)>0,U=u(1);else,U=0;end, % NB u(1)/60000 est en l/mn !!!
dx3 = ( U - Sc*sqrt(2*g*H2) ) / S;
dx2 = Sc*( sqrt(2*g*H2) - sqrt(2*g*H1) ) / S;
dx1 = ( Sc*sqrt(2*g*H1) - U ) / S;
sys = [dx1,dx2,dx3];
% End of mdlUpdate.
%==============================================================
% Calculate outputs
%==============================================================
function sys = mdlOutputs(t,x,u)
global h T
if t>T,
    visualbac(h,5*x);
    T=T+0.1;
end,
sys = x;
% End of mdlOutputs.
function sys = mdlTerminate(t,x,u)
sys = [];
% End of mdlOutputs.