function m=rules_parser(m,rules)
%RULES_PARSER parses rules in order to populate the rules
%    base of a mamdani model
%    
%    M=RULES_PARSER(M,RULES) 
%    
%    See also: 
%    
%    

%MAN_PAGE_BEGIN
%
%   @purpose	parses rules in order to populate the rules base of a mamdani model.
%
%   @synopsis	m=rules_parser(m,rules)
%   @description  
%
%   @see 
%
%MAN_PAGE_END

% By Antoine Duchateau. All Rights Reserved.
% Written: 27/08/99


if iscell(rules),
	for i=1:length(rules),
		m = parse_rule(m,rules{i});
	end
else
	fid = fopen(rules);
	s = fscanf(fid,'%c');
	fclose(fid);
	
	flag = 1;
	
	while flag,
		[l,s] = strtok(s,13);
		if isempty(l),
			flag = 0;
		else
			m = parse_rule(m,l);
		end
	end
end

function m = parse_rule(m,r)

rls = zeros(1,get(m,'n_in')+get(m,'n_out'));

[tok,r] = strtok(r);
tok = fliplr(deblank(fliplr(deblank(tok))));

if ~strcmp(tok,'if'),
	error('Rule definition should begin with an if');
end

flag = 1;
sr = '';

while flag,
	[tok,r] = strtok(r);
	tok = fliplr(deblank(fliplr(deblank(tok))));

	if isempty(tok),
		flag = 0;
	elseif strcmp(tok,'and')|strcmp(tok,'then'),
		sr = sr(2:end);
		lim = findstr(sr,' is ');
		firstpart = sr(1:lim-1);
		secpart = sr(lim+4:end);
		nvar = find(strcmp(m.varnames,firstpart))
		rls(nvar) = find(strcmp(m.ling{nvar},secpart));
		sr = '';
	else
		sr = [sr ' ' tok];
	end
end

m.rls = [m.rls; rls];
m.n_rules = m.n_rules + 1;
