function eta=unfixpar(etaold,mat1,arg1)
%UNFIXPAR	Unfixes parameters in state-space ans ARX model structures
%
%	TH = unfixpar(TH_OLD,MATRIX,ELEMENTS)
%
%	TH : The new theta-matrix
%	TH_OLD: The old theta-matrix
%	MATRIX: What matrix to manipulate 
%		(one of 'A','B','C','D','K' or 'X0')
%	ELEMENTS: Which elements to manipulate; an n by 2 matrix, where
%		each row contains the row- and column numbers
%		of the elements in question.
%
%	Example: th1 = unfixpar(th,'A',[3,1;2,2;1,3]);
%
%       If MATRIX is given the value 'A1', 'A2', etc or 'B0', 'B1' etc
%	the manipulations will be obtained in the corresponding matrix
%	in an ARX-structure, provided TH_OLD is defined as such.
%
%	Note: UNFIXPAR works only on standard model structures
%	originally defined by MS2TH, ARX2TH or ARX; if TH_OLD is based on a
%	user-defined structure (by MF2TH), you must unfix it yourself


%	L. Ljung 10-2-90
%	Copyright (c) 1990 by the MathWorks, Inc.
%	All Rights Reserved.

if nargin<3, arg1=[];end
[nr,nc]=size(etaold);
if ~isthss(etaold) ,[a,b,c,d,f,lam]=th2poly(etaold);[nu,nf]=size(f);
if max([nf length(c) length(d)])==1, etaold=arx2th(a,b,1,1,lam,etaold(1,2));
else
error('This routine is meaningful only for standard state-space structures (originally created by ms2th) and arx structures')
end ,end

if ~any(etaold(2,8)==[1 2 3]), 
error('This routine is meaningful only for standard state-space structures (originally created by ms2th) and arx structures')
end 


[nr,nc]=size(etaold);
nd=etaold(1,5);
ms=getargth(etaold);[par,P,lambda]=th2par(etaold);
[rms,cms]=size(ms);
if etaold(2,8)==3,arx=1;else arx=0;end
if etaold(2,8)==1,cd='c';else cd='d';end
T=etaold(1,2);
if T>0 & etaold(2,8)==1, 
error('This structure is marked as discrete-time, while the underlying parametrization is continuous-time. Do thd2thc first!'),end

if mat1(1)~='x' & mat1(1)~='X'
  if length(mat1)>1 
     if ~arx
	error('This option can be used only for ARX-models')
     end
     etapar=etaold(3,1:nd);
     arg=getargth(etaold);
     [rarg,carg]=size(arg);
     as1=arg(:,1:rarg);
     nr=find(sum(as1')==0);
     [as,bs,cs,ds]=ssmodx9(etapar,-1,arg);%FIXA
     [ny,nz]=size(cs);[nx,nz]=size(as);[nz,nu]=size(bs);
     na=(nr(1)-1)/ny;
     if nu>0,nb=(nx-na*ny)/nu;else nb=0;end    
     
     mnr=eval(mat1(2:length(mat1)));
     if mat1(1)=='a' | mat1(1)=='A'
        if mnr>na, error('Matrix number exceeds model order!'),end
     mat1='a'; arg1(:,2)=arg1(:,2)+(mnr-1)*ny;
     end
     if mat1(1)=='b' | mat1(1)=='B'	
        if mnr>nb, error('Matrix number exceeds model order!'),end
        if mnr==0, mat1='b'; 
        else mat1='a';arg1(:,2)=arg1(:,2)+na*ny+(mnr-1)*nu;
        end
	if na==0,if mnr==0,mat1='d';else mat1='c';
	arg1(:,2)=arg1(:,2)+(mnr-1)*nu;end,end
     end
   end
end 

[ms,par]=unfixxx(ms,par,mat1,arg1);
[rms,cms]=size(ms);
if arx, ms(1,cms)=-abs(ms(1,cms));end
eta=ms2th(ms,cd,par,lambda,abs(T));
eta(2,7)=26;
if arx, eta(2,8)=3;eta(2,7)=36;end

