% decompose the theory into clauses, and insert clauses
% using candidate hypothesis output into the file.

% input is a list with [1-[...],2-[...] ...]
insertTheories([],Tree,Tree).
insertTheories([EI|EIs],TreeSoFar,Tree):-
	findall(Index,candidateH0(EI,Index,T),Indexes),
	insertOneEI_Ts(Indexes,EI,TreeSoFar,NTreeSoFar),
	insertTheories(EIs,NTreeSoFar,Tree).

insertOneEI_Ts([],EI,Tree,Tree).
insertOneEI_Ts([TI|TIs],EI,TreeSoFar,Tree):-
	candidateH0(EI,TI,T),
	insertClas(T,EI-TI,TreeSoFar,NTreeSoFar),
	insertOneEI_Ts(TIs,EI,NTreeSoFar,Tree).


		/*(append(Pre,[EI|Post],EI_List)->
			NTreeSoFar=TreeSoFar;
			rb_update(TreeSoFar,ClaI,[EI|EI_List],NTreeSoFar)
		); */	% -- this part is not part of this program -- it is the old version where only count the EI

/* This program count as EI-[TI1,TI2,TI3,...]
insertClas([],EI-TI,Tree,Tree).
insertClas([ClaI|ClaIs],EI-TI,TreeSoFar,Tree):-
	(rb_lookup(ClaI,EI_List,TreeSoFar)->
		%ClaI is there-> previous example, or the same example
		(append([EI-TIs],PreRecord,EI_List)->					
			%rb_update(TreeSoFar,ClaI,[EI-[TI|TIs]|PreRecord],NTreeSoFar); % assume there is no redundant(repeated) clauses in the theory 
			(TIs=[TI|RestTIs] ->
				NTreeSoFar=TreeSoFar; % there is redundant(repeated) clauses in the theory - so nothing to update % this applies to np:-det,noun appear twice in one sentence-- this save the effort to remove duplicate
				rb_update(TreeSoFar,ClaI,[EI-[TI|TIs]|PreRecord],NTreeSoFar)
			);
			rb_update(TreeSoFar,ClaI,[EI-[TI]|EI_List],NTreeSoFar)
		);
				
		rb_insert(TreeSoFar,ClaI,[EI-[TI]],NTreeSoFar)
	),	
	insertClas(ClaIs,EI-TI,NTreeSoFar,Tree).
*/


%/* % this program simply count the clauses as [EI1-TI1,EI1-TI2, ... ]
insertClas([],EI-TI,Tree,Tree).
insertClas([ClaI|ClaIs],EI-TI,TreeSoFar,Tree):-
	(rb_lookup(ClaI,EI_List,TreeSoFar)->
		%ClaI is there-> previous example, or the same example but different TI -- since you 
		(EI_List=[EI-TI|RestEITIs]->
			NTreeSoFar=TreeSoFar;		% there is redundant(repeated) clauses in the theory 
			rb_update(TreeSoFar,ClaI,[EI-TI|EI_List],NTreeSoFar)
		);		
		rb_insert(TreeSoFar,ClaI,[EI-TI],NTreeSoFar)
	),	
	insertClas(ClaIs,EI-TI,NTreeSoFar,Tree).
%*/





