% identify which candidateH is shared with other, only them are considered later for cross product

indentifySharedHs(PosEIs):-
	tell('candidateH.pl'), %tell('grammar_candidateH.pl'),	
	genAll(PosEIs,AllTs,TotalNum),%genAll_EIsigned(PosEIs,AllTs,TotalNum),
	write('%Total is '), write(TotalNum),nl,
	%print_list(AllTs),nl,
	told,
	consult('candidateH2.pl'),	%consult('grammar_candidateH.pl'),
	
	%tell('tomatoCountedResult.pl'),
	score each candidate H and asserta the fact score(EI,TI,Score).

	rb_new(Tree0),
	reverse(PosEIs,PosEIsReversedOrder),
	insertTheories(PosEIsReversedOrder,Tree0,Tree), % insertTheories(AllTs,Tree0,Tree) *** be careful about the function you are using
	%scoreAll(AllTs,Tree,ScoredEIsTs).
	rb_visit(Tree,T_EITIs),%print_list(T_EITIs),

	maplist(outputSharedInfo,T_EITIs). % go through and output info--preparing for generate module



outputSharedInfo([rs-{RID,LimitingType,Change,Time}]-EITIs):-    
	exExtraction(EITIs,EIs),
     	length(EIs,EINum),EINum>1,!,
	outputSharedInfo0(rs-{RID,LimitingType,Change,Time},EITIs).

outputSharedInfo(ClaID-EITIs). % do nothing for met, and those sinlgeEI rs.


outputSharedInfo0(rs-{RID,enzymeLimiting,Change,Time},EITIs):-
	asserta(sharedControl_reaction({RID,Change,Time},EITIs)).
outputSharedInfo0(rs-{RID,substrateLimiting,Change,Time},EITIs):-
	asserta(sharedSL_channel({RID,Change,Time},EITIs)).

modulesGeneration:- 
	findall({RID,Change,Time}-EITIs,
		sharedControl_reaction({RID,Change,Time},EITIs),
		Candidate_controlPoints),
	maplist(generateOneModule,Candidate_controlPoints). % -> produce a module.

% take care of combinable. -- what if their shortest one are not combinable (in terms of metabolite): alternatives for the one that's longer , no alternative then remove that branch (skip that EI).  
%-- order by length and number of alternatives
% what if I do cross product -- is it easier -- no, because of the integrity constraint

generateOneModule({RID,Change,Time}-EITIs,{RID,Change,Time}):-
	findall(
		member(EI-TI,EITIs),
	SharedChannels),

	SharedChannels\==[].
	

generateOneModule({RID,Change,Time}-EITIs,{RID,Change,Time}):-
	ti_GroupedByEI(EITIs,EIs_ti),
	maplist() % get the smallest for each EIs








%indentifySharedControlRections([met-Record]-EITIs):-!. % do nothing
%indentifySharedControlRections([rs-{RID,substrateLimiting,Change,Time}]-EITIs):-!. 
identifySharedControlRections([rs-{RID,enzymeLimiting,Change,Time}]-EITIs):-    
      ti_GroupedByEI(EITIs,EIs),
      length(EIs,EINum),EINum>1,!,
      asserta().


identifySharedControlRections(ClaID-EITIs). % do nothing

% 
ti_GroupedByEI([],[]).
ti_GroupedByEI([EI-TI|Record],EIs):- 
	ti_GroupedByEI(Record,PreEIs),
	(PreEIs=[EI-TIs|Rest] ->
		EIs=[EI-[TI|TIs]|Rest];
		EIs=[EI-[TI]|PreEIs]
	).



score for substrate limiting 
-- preference on non-reversible direction. 
-- preference on noChange?
otherwise, I can simply count the length