% Function to compute rates of change of demand and supply functions
% in the deterministic queueing model

% Programmer: A. Trani
% Includes extensions to produce cumulative demand (p(4)) and supply tables
% (p(5))

% Given inputs to the problem:
%
% demand = demand function (lambda) as a function of time (t)
% capacity = Supply = Capacity function (mu) as a function of time (t)
% time = Time vector (units of time up to you and defined by the problem context)

% Outputs of the problem:

% p(1) = L(t) = queue length as a function of time
% p(2) = A(t) = area under the queue length function (~ total delay).
% p(2) is the Integral of L(t)

% Units of L(t) are entities (aircraft, passengers, etc.)
% Units of A(t) are entities-time (aircraft-hours, passenger-hours, etc.)

%
% Two state variables in the system
% p(1) = L(t) = L(t-1) + [demand(t) - supply(t)] (dt)	            % queue length 
% p(2) = A(t) = A(t-1) + [L(t)] (dt)					                        % area under L(t) curve

function pprime = fqueue_deterministic_mod(t,p)

global demand capacity time

% Define the rate equations

demand_table 	= interp1(time,demand,t);
capacity_table 	  = interp1(time,capacity,t);

if (demand_table < capacity_table) & (p(1) > 0)
	pprime(1) = demand_table - capacity_table;	% rate of change in state variable
elseif demand_table > capacity_table
	pprime(1) = demand_table - capacity_table;	% rate of change in state variable
else
	pprime(1) = 0.0;				% avoids accumulation of entities if queue length is zero
end

pprime(2) = p(1);					% integrates the delay curve over time

% Enhancements to calculate cumulative demand and cumulative capacity
pprime(3) = demand_table;           % acumulates the demand table

% p(4) = cumulative demand curve
% p(5) = cumulative supply curve

if demand_table <= capacity_table & (p(1) <= 0)
	pprime(4) = demand_table ;	% rate of change in demand
    pprime(5) = demand_table ;	% rate of change in supply equals demand since supply > demand
else  %  & (p(1) > 0)
    pprime(4) = demand_table ;	% rate of change in demand
    pprime(5) = capacity_table ;	% rate of change in supply
end

pprime = pprime';