%copyright T.J. Mc Avoy 1998
% Function to replace a valve with a setpoint to an inner cascade control
% system in the process steady state gain matrix.  The valve to be 
% replaced is m =1:4, 6:11, and the setpoint to be manipulated is j = 1:4, 10, 
% 14, 17, 19, 21:22.  Note that the m's and j's have to be  paired correctly.
% Correct pairings are: 1-2, 2-3, 3-1, 4-4, 6-10, 7-14, 8-17, 9-19, 10-21,
% and 11-22.  These pairings correspond to the 8 flow cascades and the
% 2 temperatures cascades.  Valve 5 and the agitator 12 cannot be used in
% a cascade arrangement. The returned gain matrix K has zeros in its j th row, and a
% 1. in the column corresponding to valve m. After the appropriate number of 
% cascades have been closed, the rows associated with the cascades can be
% eliminated from the final K matrix if desired.   The level pairings have to be input
% so that the correct column is assigned to m.  The labels are updated by the routine.
% This routine works on the non-analyzer loops.
% function [A,Glabel]=cascade1(K,lev,Glabel) old code
function [A,Glabel]=cascade1(K,Glabel)
error=0;
loop=1;
disp('FOR THE STUDENT EDITION OF MATLAB IT MAY BE NECESSARY TO')
disp('REPLACE THE FUNCTION sprintf(..) WITH input(..)')

[s1,s2]=size(Glabel);
[s3,s4]=size(K);
A=K;
disp(' ')
disp('THE 10 MANIPULATED VARIABLES WHICH CAN BE CASCADED ARE:')
disp(' ')
disp('MV 1  =  D-FEED VALVE')
disp('MV  2 =  E-FEED VALVE')  
disp('MV  3 =  A-FEED VALVE')
disp('MV  4 =  C-FEED VALVE')
disp('MV  6 =  PURGE VALVE')
disp('MV  7 =  SEPARATOR UNDERFLOW VALVE')
disp('MV  8 =  PRODUCT VALVE')
disp('MV  9 =  STEAM VALVE')
disp('MV 10 =  REACTOR COOLING WATER VALVE')
disp('MV 11 =  CONDENSER COOLING WATER VALVE')
disp(' ')
disp('PRESS RETURN TO CONTINUE')
pause
disp(' ')
s=sprintf('INPUT MV TO BE CASCADED%3.0f');
disp(s)
mm = input(''); 
mt = round(mm);   % ROUNDS OFF SELECTION 
m = mt;
while loop==1
if m==5|m==12;disp('CANT CHOOSE THIS MV. TRY AGAIN.');error=1;break;end;
if m<1|m>12;disp('VALVE CHOICE IS OUT OF RANGE. TRY AGAIN.');error=1;break;end;
if m==1
	j=2;
	s='  D Feed Flow SP';
	elseif m==2
	j=3;
	s='  E Feed Flow SP';
	elseif m==3
	j=1;
	s='  A Feed Flow SP';
	elseif m==4
	j=4;
	s='  C Feed Flow SP';
	elseif m==6
	j=10;
	s='   Purge Flow SP';
	elseif m==7
	j=14;
	s='Sep Exit Flow SP';
	elseif m==8
	j=17;
	s=' Product Flow SP';
	elseif m==9
	j=19;
	s='   Steam Flow SP';
	elseif m==10
	j=21;
	s='  Reactor CW SP ';
	else
	j=22;
	s='  Conden. CW SP ';
end
	for i=1:s3
		A(i,:)=K(i,:)-K(j,:)*K(i,m)/K(j,m);
	end
		A(:,m)=K(:,m)/K(j,m);
	break
end
if error==0;% need to change label for MV # m. Otherwise an incorrect input has been given.
	Glabel(m+1,20:35)=s;
	else
end
	

