% Copyright (C) 2003 Fred Mesnard <fred@univ-reunion.fr>
%
% This file is part of cTI.
%
% cTI is free software; you can redistribute it and/or modify it
% under the terms of the GNU General Public License as published by the
% Free Software Foundation; either version 2 of the License, or (at your
% option) any later version.
%
% cTI is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
% FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
% for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
% USA.
%
% For the most up-to-date information see the cTI's web site:
% http://www.cs.unipr.it/cTI/

:- module(num_add_model_al,[add_model_after_litt/4]).

:- use_module(library(lists),[append/3,remove_duplicates/2]).
:-use_module(utils).
:-use_module(db).

add_model_after_litt(LPRs1,Db,IdModel,Sccs) :-
	%trace,
	add_model0(LPRs1,Db,IdModel,Sccs).

add_model0([],_Db,_IdModel,[]).
add_model0([Ps|Pss],Db,IdModel,[Qs|Qss]) :-
	add_model1(Ps,Db,IdModel,Qs),
	add_model0(Pss,Db,IdModel,Qss).

add_model1([],_Db,_IM,[]).
add_model1([P/N-Rs|LPRs],Db,IdM,[P/N-Qs|Qss]) :-
	add_model2(Rs,P,N,Db,IdM,Qs),
	add_model1(LPRs,Db,IdM,Qss).
	
add_model2([],_P,_N,_Db,_IM,[]).
add_model2([Ref|Rs],P,N,Db,IdM,[Cl|Cls]) :-
	clause_head(Ref,H),
	clause_body(Ref,Bs),
	specialize(Bs,Db,IdM,Bs2),
	simp(Bs2,Bs3),
	build_clause(H,Bs3,Cl),
	add_model2(Rs,P,N,Db,IdM,Cls).
	
specialize([],_Db,_IdM,[]).
specialize(['$predef'(P)|Bs],Db,IdM,['$predef'(P)|Bs2]) :-
	!,specialize(Bs,Db,IdM,Bs2).
specialize(['$constraint'(Cs)|Bs],Db,IdM,['$constraint'(Cs)|Bs2]) :-
	!,specialize(Bs,Db,IdM,Bs2).
specialize([B],_Db,_IdM,[B]) :-!.
specialize([B|Bs],Db,IdM,[B,'$constraint'(Cs)|Bs2]) :-
	functor(B,P,N),B=..[P|Vars],
	get_db(P,N,IdM,Db,Vars-Cs-_Prec-_Ite),
	specialize(Bs,Db,IdM,Bs2).

simp([],[]).
simp(['$predef'(P)|Bs],['$predef'(P)|Cs]):-!,simp(Bs,Cs).
simp(['$constraint'(As),'$constraint'(Bs)|Cs],['$constraint'(Fs)|Ds]):-
	!,append(As,Bs,Es),
	remove_duplicates(Es,Fs),
	simp(Cs,Ds).
simp([B|Bs],[B|Cs]):-simp(Bs,Cs).
