function m=fit_linears(m,in,out,type)
%FIT_LINEARS identifies the consequent part of a fuzzy
%    model from data
%    
%    M=FIT_LINEARS(M,IN,OUT,TYPE)  identify model M on the
%    basis of the data inside IN and OUT.TYPE is used to
%    specify the type of the fit. 0 is the defaults and leads
%    to a classical LMS fit. 1 leads to a local fit.
%    
%    

%MAN_PAGE_BEGIN
%
%   @purpose   identifies the consequent part of a fuzzy model from data.
%
%   @synopsis m=fit_linears(m,in,out,type) 
%   @description  identify model <CODE>m</CODE> on the basis of the data
%   inside <CODE>in</CODE> and <CODE>out</CODE>.<CODE>type</CODE> is used to
%	specify the type of the fit. 0 is the
%   defaults and leads to a classical LMS fit. 1 leads to a local fit.
%
%MAN_PAGE_END   

if nargin<4,
	type = 0;
end

n_rules=get(m,'n_rules');
n_in=get(m,'n_in');

long_x=[in ones(size(in,1),1)];

members=membership(m,in);

if strcmpi(m.model_code{2},'ungaussian')|strcmpi(m.model_code{2},'uninversedist'),
	sum_memb=ones(size(members));
	alphas = members;
else
	sum_memb=sum(members,2)+realmin;
	alphas=(members./sum_memb(:,ones(1,n_rules)));
end

if type,
	for i=1:n_rules,
		m.linears(:,:,i)=((sqrt(alphas(:,i*ones(n_in+1,1))).*long_x)\(sqrt(alphas(:,i)).*out))';
	end
else
	i1=1:n_rules;
	i2=i1(ones(1,n_in+1),:);
	i3=(1:n_in+1)';
	i4=i3(:,ones(1,n_rules));
	
	theA=alphas(:,i2).*long_x(:,i4);
	
	theB=out;
	theL=theA\theB;
	m.linears = reshape(theL,1,n_in+1,n_rules);
end
