function out=eval(m,varargin)
%EVAL computes the value of the model
%    
%    This function returns the output of system as computated
%    by the model, given  a regressor. 
%    
%    OUT=EVAL(M,X,J) returns the value OUT for the output(s) J
%    of model M given the input X.
%    
%    

%MAN_PAGE_BEGIN
%
%   @purpose  computes the value of the model. This function
%   returns the output of system as computated by the model, given 
%   a regressor. 
%   
%   @synopsis out=eval(m,x,j)
%   @description  returns the value <code>out</code> for the output(s) <code>j</code> of
%   model <code>m</code> given the input <code>x</code>.
%
%MAN_PAGE_END

%    version 1.0
%
%  Antoine Duchateau, 10/12/1997
%


error(checkargs([{m} varargin],[2 3],'mamdani','numeric','numeric'));

x = varargin{1};
if (nargin == 2)|isempty(varargin{2}),
	j = 1:get(m,'n_out');
else
	j = varargin{2};
end
ni = get(m,'n_in');

and_code = m.model_code{1};
defuzz_code = m.model_code{2};

mf = membership(m,x)';

if strcmp(defuzz_code,'meancentroid'),
	for i=j,
		dfuzz{i} = mf;
		c = mfs{i+ni}(rls(:,i+ni),2:5);
		centers{i} = ((c(:,2) - c(:,1)).*(2*c(:,2) + c(:,1))/3+ (c(:,3) - c(:,2)).*(c(:,3) + c(:,2))...
					+(c(:,4) - c(:,3)).*(2*c(:,3) + c(:,4))/3)/(c(:,4) + c(:,3) - c(:,2) - c(:,1));
	end
		
elseif  strcmp(defuzz_code,'centergravity'),
	for i=j,
		c = mfs{i+ni}(rls(:,i+ni),2:5);
		c(:,2) = c(:,1) + (c(:,2) - c(:,1)) .* mf;
		c(:,3) = c(:,4) - (c(:,4) - c(:,3)) .* mf;
		centers{i} = ((c(:,2) - c(:,1)).*(2*c(:,2) + c(:,1))/3+ (c(:,3) - c(:,2)).*(c(:,3) + c(:,2))...
					+(c(:,4) - c(:,3)).*(2*c(:,3) + c(:,4))/3)/(c(:,4) + c(:,3) - c(:,2) - c(:,1));
		defuzz{i} = (c(:,4) - c(:,1) + c(:,3) - c(:,2)) .* mf / 2;
	end
end

for i=1:length(j),
	out(i) = sum(defuzz{j(i)}.*centers{j(i)})/(sum(defuzz{j(i)}+realmin);
end

