% function sys = fitsys(resp,ord,wt,code)
%
%   FITSYS fits frequency response data in RESP
%   with a transfer function of order ORD, using a
%   frequency dependent weight in WT (optional).
%
%   To normalize the effect of high freq .vs. low freq
%   on the fit, the program appends an additional
%   frequency dependent weighting to the user supplied
%   weighting WT. The correction is equal to (1/omega.^ord)
%   at each frequency point, omega.
%
%   The fourth argument, CODE, is optional. If set
%   to 0 (default), then the fit is returned unchanged
%   from the INVFREQS function return. If CODE = 1, 
%   as in the mu-synthesis routines, it forces the fit
%   to be stable, minimum phase, simply by reflecting the 
%   poles and zeros if necessary. Typically in this case, 
%   the response RESP comes from the program GENPHASE,
%   and already corresponds to a stable, minimum phase
%   transfer function.
%
%  See also: FITMAG, MAGFIT, GENPHASE, INVFREQS, MUSYNFIT, and MUSYNFLP.

%change has been made by Wes Wang at the MathWorks in 5/12/92
%
function sys = fitsys(resp,ord,wt,code)
 if nargin <= 1
   disp(['usage: sys = fitsys(resp,ord,wt,code)']);
   return
 end
 [rtype,rrows,rcols,rnum] = minfo(resp);
 gjw    =  (resp(1:rnum,1)).';        % row vector
 omega  =  (resp(1:rnum,2)).';        % row vector
 if ord == 0
   ordwt = 1;
 else
   ordwt = nd2sys([1],[1 zeros(1,ord)]);
 end
 ordwt_g = vabs(frsp(ordwt,resp));
 wtjw = (ordwt_g(1:rnum,1)).';        % row vector

 if nargin == 2
   [b,a] = invfreqs(gjw,omega,ord,ord,wtjw);
   code = 0;
 elseif nargin >= 3
   [wttype,wtrows,wtcols,wtnum] = minfo(wt);
   if wttype == 'vary'
     if wtrows == 1 & wtcols == 1
       wtjw = abs((wt(1:wtnum,1))).' .* wtjw ;
       [b,a] = invfreqs(gjw,omega,ord,ord,wtjw);
     else
       error('weighting function must be 1x1 VARYING matrix')
       return
     end
     if nargin == 3
       code = 0;
     end
   elseif wttype == 'cons'
     [b,a] = invfreqs(gjw,omega,ord,ord,wtjw);
%%%%%%% Change has made here --- Wes Wang %%%%%%%%
% original code
%     code = wt;
%%%%%%% change to be
     code = 0;
   else
     error('third argument shouldn''t be a SYSTEM');
     return
   end
 end
 if code == 1           
   b = refroots(b);
   a = refroots(a);
 elseif code ~= 0
   error('last argument must be 0 or 1')
   return
 end
 if ord == 0
   sys = b/a;
 else
   if max(real(roots(a)))<0
     sys = sysbal(nd2sys(b,a));
   else
     sys = nd2sys(b,a);
   end
 end
%
% Copyright MUSYN INC 1991,  All Rights Reserved
