function [av,steadyStatePI] = nma_HW_12_3(lambda,mu,m,n,s)
%
%function nma_HW_12_3(lambda,mu,m,n,s)
%solves problem 12.3 in lecture notes by Professor Gearhart,
%CSUF Mathematics 504, spring 2008
%
%by Nasser Abbasi
%
%INPUT:
%  lambda, mean time between breakdown of machines
%  mu,     mean service time
%  m,      maximum number of operating machines
%  n,      maximum number of spare machines
%  s,      number of servers.  1<=s<=m
%
%OUTPUT:
%  av,     The expected number of days a machine stays in the
%          queue (or in the repair shop)

av    = -1;
DEBUG = 0;

[msg,status] = validInput(lambda,mu,m,n,s);
if ~status
    error(msg);
end

%
% Allocate data storage
%
nStates       = n+m+1;
steadyStatePI = zeros(nStates,1);
factors       = zeros(nStates-1,1);
mus           = zeros(nStates-1,1);
lambdas       = zeros(nStates,1);

%
%  Make the Lambda vector
%
for i=0:n+m
    if i<=n
        lambdas(i+1)=m*lambda;
    else
        lambdas(i+1)=(m+n-i)*lambda;
    end
end

%
%  Make the mu vector
%
for i=1:n+m
    if i<s
        mus(i)=i*mu;
    else
        mus(i)=s*mu;
    end
end

%
%  build the factors lambda/mu terms
%
factors(1)=lambdas(1)/mus(1);
for i=2:n+m
    factors(i)=factors(i-1)*lambdas(i)/mus(i);
end

%
% Find mu_0 and initialize PI vector
%
muZero=1/(1+sum(factors));
steadyStatePI(1)=muZero;

%
% calculate the rest of the steady state PI vector
%
for i=2:nStates
    steadyStatePI(i)=factors(i-1)*muZero;
end

%
% verify sum is ONE
%
if DEBUG
    fprintf('sum of PI vector is %f\n',sum(steadyStatePI));
end

%Find expected value
av=0;
for i=0:n+m
    av=av+i*steadyStatePI(i+1);
end

%%%%%%%%%%%%%%
% Function to validate input
%
%%%%%%%%%%%%%%
function [msg,status] = validInput(lambda,mu,m,n,s)
VALID     = 1;
NOT_VALID = 0;

status = NOT_VALID;
msg    = '';

if ~isnumeric(s) || ~isnumeric(m) || ~isnumeric(n) ...
        ||  ~isnumeric(mu) ||  ~isnumeric(lambda)
    msg='not a numeric value in input. correct';
    return;
end

if s<=0 || m<=0 || n<0 || lambda<=0 || mu <=0
    msg='negative value in input. correct';
    return;
end

if s>n+m
    msg='number of servers must be less than n+m';
    return;
end

status=VALID;
