% Fall 2015, CDA6530.
% discrete event simulation lecture
% M/D/1 queue problem simulation
% use the notations in lecture notes (discreteEvent-simulation)

% suppose arrival follows Poisson process with rate \lambda
% suppose service time follows deterministic time of fixed time of 
% 1/(\lambda*2).

lambda = 0.5;  serviceTime = 1/(lambda*2);
Na = 0; Nd = 0; n = 0;
simulN = 20;  % simulation ends when this number of customer has 
                % arrived at the queue
A_output = inf*ones(1, simulN);
D_output = inf*ones(1, simulN);
t_a = -log(rand)/lambda; Y = serviceTime; t_d = Y + t_a;
arrivalNum  = 0; eventNum = 0; SystemState = zeros(2*simulN,1);
SystemStateTime = SystemState;
while arrivalNum < simulN,
    if t_a <= t_d,  % arrival event
        n = n+1;
        t = t_a;
        eventNum = eventNum + 1;
        SystemState(eventNum) =  n;
        SystemStateTime(eventNum) = t;
        arrivalNum = arrivalNum+1;
        Na = Na + 1;
        t_a = t - log(rand)/lambda; % next arrival time
        if n ==1,
            Y = serviceTime; t_d = t + Y;
        end
        A_output(Na) = t;
    else
        % departure event
        t = t_d;
        n = n-1;
        eventNum = eventNum + 1;
        SystemState(eventNum) =  n;        
        SystemStateTime(eventNum) = t;
        Nd = Nd + 1;
        if n==0, 
            t_d = inf;
        else
            Y = serviceTime; t_d = t + Y;
        end
        D_output(Nd) = t;
    end
end
% output display of n, the number of customers in queue
plot(SystemStateTime(1:simulN-1), SystemState(1:simulN-1), 'ro-'); 
% the last customer does not have the departure time yet.

        


