function [K,q] = mcerlc(A,h,N,Q,I,K0)
% Call [K,q] = mcerlc(A,h,N,Q,I,K0)
%Where A = offered traffic in Erlang (for M/x queue lambda = A/h)
%      k = holding time is seconds   (For M/x queye mu =1/h)
%      N = Number of resources
%      Q = maximum queue length
%      I = number of attempts/arrivals to process
%      K0 = optional staring State, Defaults to integer below A
%Returns
%      K = sequence of call states visited
%      q = sequence of queued call states visited

if (nargin == 5)
  K0 = fix(A); 
endif
M=N+Q

% Initialise rate parameters for Erlang C 
s = ones(1,M+1)*A/h
e = [(0:N)/h,ones(1,Q)*N/h]

k=K0+1; % corresponding to starting state 
i=1; % iteration counter

% Markov Chain Engine 

do 
  r=rand(1,1);
  if (r < e(k))
    k = max(1,k-1);
  elseif (r < e(k)+s(k))
    k = min(M+1,k+1);
  endif     % Do nothing case is implicit
  K(i) = k-1;
  i=i+1;
until (i>I)

%Split actve and queued users
j = find(K>N);
q=zeros(1,I);
q(j)=K(j)-N;
K(j)=N; 


