function [ newQN ] = scMerge( qn, indexA, indexB, sc )

%SCMERGE software component merge as software refactoring
%   It takes a QN with the indexA of the A-th and B-th queueing center
%   where to apply the merge of certain software components.
%   Note that it works only if indexB > indexA
% INPUT
% qn: initial queueing network
% indexA: index of the first queueing center to merge
% indexB: index of the second queueing center to merge
% sc: software component mergeability set
% OUTPUT
% newQN: refactored QN
    
newM = qn.M - 1;

newS = [qn.S(1:(indexB-1));qn.S((indexB+1):end)];

newRates = [qn.rates(1:(indexB-1),:); qn.rates((indexB+1):end,:)];

newRates(indexA,:)=sc;

newSched = [qn.sched(1:(indexB-1));qn.sched((indexB+1):end)];

newP = zeros(qn.K*newM, qn.K*newM);

%visits = avgVisits(qn);

%demands = avgDemands(qn,visits);

%kbig = find(max(demands(index,:)) == demands(index,:));

for kk=1:qn.K
    Pk = qn.P(kk:qn.K:end, kk:qn.K:end);
    newPk = [Pk(1:(indexB-1),:); Pk((indexB+1):end,:)];
    newPk = [newPk(:,1:(indexB-1)) newPk(:,(indexB+1):end)];
    
    selection = [1:(indexB-1) (indexB+1):qn.M];
    
    newPk(:,indexA) = Pk(selection, indexA) + Pk(selection, indexB);
    newPk(indexA,:) = Pk(indexA, selection) + Pk(indexB, selection);
    newPk(indexA,indexA) = Pk(indexB, indexA);
    
    newP(kk:qn.K:end, kk:qn.K:end) = newPk;
end

newRefNodes = qn.refNodes;
	newRefNodes(newRefNodes>indexB) = newRefNodes(newRefNodes>indexB) - 1;
    
newNodeNames = qn.nodeNames;
newNodeNames(indexB) = [];
% = [qn.nodeNames(1:(indexB-1));qn.nodeNames(index:end)];

% create new queuing network
	%if isa(qn,'CMCQNCSRE')
		%newQN = CMCQNCSRE(newM, qn.K, qn.E, qn.N, qn.ENV, newS, newRates, newSched, ...
		%	newP, qn.NK, qn.classMatch, newRefNodes, qn.resetRules, ...
		%	newNodeNames, qn.classNames, qn.adhocResetRules);
	%else
		newQN = CMCQNCS(newM, qn.K, qn.N, newS, newRates, newSched, newP, qn.NK, ...
			qn.classMatch, newRefNodes, newNodeNames, qn.classNames);
	%end

%	disp(['Merging QN' num2str(indexA) '+QN' num2str(indexB) ' old1=<' num2str(qn.rates(indexA,:)) '> ' ...
%		'old2=<' num2str(qn.rates(indexB,:)) '> new=<' num2str(sc) '>']);
end

