function [ newQN ] = allocateQN(qn, d, resources)
%ALLOCATEQN Allocate a queuing network according to an allocation matrix.
%   qn: queuing network
%	 d: allocation matrix
%	 resources: set of available resources
%	 allocatedQN: new QN allocated 

	allocatedQN = qn;
	[x, y] = size(d);
	allocation = d./repmat(sum(d,2),1,y);
	ii = qn.M + 1;
	delayNodes = getDelayNodes(qn);
	bestfitResource = resources.bestFitResourceIndex(sum(d,1));
	cpu = resources.cpu(bestfitResource);
	
	while x>0
		% start from the last element
		ii = ii-1;
		
		% exclude delay nodes
		if delayNodes(ii)
			continue;
		end
		x = x-1;
		
		if any(allocation(x+1,:)>=1-eps)
			continue;
		end
		allocatedQN = splitStation(allocatedQN, ii, allocation(x+1,:), cpu);
	end
	
	newQN = allocatedQN;
	
end


