This is a simulation for a single server overlapping time intervals. Intervals are exponentially generated random variables (poisson process). I want time passed closing and average time spent in the store. Is it doing what i want and can I make it better. Thanks

oh P.S. X(lam) is a function i call up to generate the exp. random variable.

A=zeros(1,10); D=zeros(1,10); Tp = 0; % time past close

avg = 0; % average time in the system

t=0; na=0; nd=0; n = 0; %start time, number of arrivals, num of departures, num of cust

ta = -log(rand)/lam; %first arrival

td = inf; % departure time unending

T = 8; % Store open for 8 hours

while ta <= T

if ta<=td

t = ta; n= n+1;

na = na + 1; A(na) = t; ta = t + X(lam);

if n ==1

td = t + X(lam);

end

else

t = td; n = n-1; nd = nd + 1; D(nd) = t; %departures

if n> 0

td = t + X(lam)

else

td = inf;

end

end

end

while n>0 % clearing the queue

t = td

nd= nd + 1

D(nd) = t;

n = n-1

td = t + X(lam);

end

Tp = max (t - T, 0);

avg = mean(D-A);

disp([Tp avg])