function [t,S,I,R] = Program_2_2(beta,gamma,mu,S0,I0,MaxTime)
%
% 
%
% RISK_STRUCTURE( beta, gamma, mu, S0, I0, MaxTime)
%      This is the MATLAB version of program 2.2 from page 27 of 
% "Modeling Infectious Disease in humans and animals" 
% by Keeling & Rohani.
% 
% It is the simple SIR epidemic with equal births and deaths.
%

% Sets up default parameters if necessary.
if nargin == 0
   beta=520/365.0;
   gamma=1/7.0;
   mu=1/(70*365.0);
   S0=0.1;
   I0=1e-4;
   MaxTime=60*365;
end

% Checks all the parameters are valid
if S0<=0 
    error('Initial level of susceptibles (%g) is less than or equal to zero',S0);
end

if I0<=0 
    error('Initial level of infecteds (%g) is less than or equal to zero',I0);
end

if beta<=0 
    error('Transmission rate beta (%g) is less than or equal to zero',beta);
end
    
if gamma<=0 
    error('Recovery rate gamma (%g) is less than or equal to zero',gamma);
end

if mu<0 
    error('Birth / Death rate gamma (%g) is less than zero',mu);
end
    
if MaxTime<=0 
    error('Maximum run time (%g) is less than or equal to zero',MaxTime);
end
    
if S0+I0>1
    warning('Initial level of susceptibles+infecteds (%g+%g=%g) is greater than one',S0,I0,S0+I0);
end

if beta<gamma+mu
    warning('Basic reproductive ratio (R_0=%g) is less than one',beta/(gamma+mu));
end

S=S0; I=I0; R=1-S-I;

% The main iteration 
options = odeset('RelTol', 1e-5);
[t, pop]=ode45(@Diff_2_2,[0 MaxTime],[S I R],options,[beta gamma mu]);

S=pop(:,1); I=pop(:,2); R=pop(:,3);

% plots the graphs with scaled colours
subplot(3,1,1)
h=plot(t,S,'-g'); 
xlabel 'Time';
ylabel 'Susceptibles'

subplot(3,1,2) 
h=plot(t,I,'-r');
xlabel 'Time';
ylabel 'Infectious'

subplot(3,1,3)
h=plot(t,R,'-g'); 
xlabel 'Time';
ylabel 'Recovereds'


% Calculates the differential rates used in the integration.
function dPop=Diff_2_2(t,pop, parameter)

beta=parameter(1); gamma=parameter(2); mu=parameter(3);
S=pop(1); I=pop(2); R=pop(3);

dPop=zeros(3,1);

dPop(1)= mu -beta*S*I - mu*S;
dPop(2)= beta*S*I - gamma*I - mu*I;
dPop(3)= gamma*I - mu*R;



