% function sys = fminter(magdata,weight,heading,osysl_g)
%
%  *****  UNTESTED  *****
%
%   FMINTER fits a stable, minimum phase transfer function
%   to magnitude data, MAGDATA, with a supplied frequency
%   domain weighting function, WEIGHT. Both these should
%   be VARYING matrices, with identical INDEPENDENT
%   VARIABLE values. FITMAG uses GENPHASE to generate
%   phase data, and FITSYS to do the fit.  OSYSL_G (optional) 
%   is the frsp of the old fit.  If given, it will be
%   displayed along with the data.
%   Identical to fitmag except that fitmaglp is used instead
%   of genphase and fitsys.  
%
%   See also: FITSYS, GENPHASE, INVFREQS, MAGFIT, MUFTBTCH,
%             MUSYNFLP and MUSYNFIT.

function sys = fminter(d,wt,heading,osysl_g)

 if nargin < 2
   disp(['usage: sys = fitmag(magdata,weight)']);
   return
 end
 if nargin == 2
   heading = [];
 end

 [dtype,drows,dcols,dnum] = minfo(d);
 if dtype ~= 'vary'
   error(['MAGDATA should be a VARYING matrix']);
   return
 end

 [wtype,wrows,wcols,wnum] = minfo(wt);
 if wtype ~= 'vary'
   error(['WEIGHT should be a VARYING matrix']);
   return
 end

 code = indvcmp(d,wt);
 if code ~= 1
    error('inconsistent VARYING data in MAGDATA and WEIGHT')
    return
 end

% vplot('liv,lm',d)    % replaced by the following code
	clg;subplot(211); 			% begin JCD CHANGE 
	 if nargin <= 3
		vplot('liv,lm',d);
 		xlabel('  data ');
	  else
		vplot('liv,lm',d,osysl_g);
 		xlabel('  data and old fit ');
	 end	
	title([heading]);
	subplot(212);
	vplot('liv,lm',wt); 
	title('wt for fit');  			%  end JCD CHANGE
 xlabel(['NOTE APPROXIMATE ORDER NECESSARY FOR FIT.....']);
 ord = input('ENTER ORDER OF CURVE FIT      ');
 while any([ isempty(ord)  (ord<0)  (floor(ord) ~= ceil(ord)) ])
     ord = input('try again - a nonnegative integer..    ');
 end


 while ord >= 0
   sysh = fitmaglp(d,[.26,.1,ord,ord],wt);
   sysh_g = frsp(sysh,d);
   rat_data = sbs(d,sysh_g);
   hhead = [',   W/ORDER = ' int2str(ord)];

%   vplot('liv,lm',rat_data)  %  replaced by the following code
	clg;subplot(211); 			% begin JCD CHANGE
	 if nargin <= 3
		vplot('liv,lm',sysh_g,resp);
 		xlabel('  1) fit    2) data ');
	  else
		vplot('liv,lm',sysh_g,resp,osysl_g);
 		xlabel('  1) fit    2) data   3) oldfit ');
	 end
	title([heading hhead]);
	subplot(212);
	vplot('liv,lm',wt); 
	title('wt for fit');			% end JCD CHANGE

   xlabel('ENTER NEW ORDER, or NEGATIVE NUMBER TO STOP ');
   pause;
   ord = input('ENTER NEW ORDER, NEGATIVE TO STOP    ');
   while any([ isempty(ord)  (floor(ord) ~= ceil(ord)) ])
       ord = input('try again - an integer, negative to stop..    ');
   end %while any
 end %while ord
sys = sysh;
subplot;
%
% Copyright MUSYN INC 1991,  All Rights Reserved
