node(N) :- innerNode(N).

extnode(0).
extnode(N) :- node(N).

leaf(L) :- extnode(L).
% leaf 0 is the left leaf
% leaf k is the right leaf of node k


% If pick_id is true, then the program assumes that the first argument of
% relation leafWeightCardinality is NOT a number, and generates
% numerical IDs for the leaves.
pick_id :- not -pick_id.

% pick a numerical id for each leaf name
leaf_id(1..X) :- num(X).
%
1{ leaf_id_name(X,LNAME) : leaf_id(X) }1 :- pick_id, leafWeightCardinality(LNAME,W,C).
1{ leaf_id_name(X,LNAME) : leafWeightCardinality(LNAME,W,C) }1 :- pick_id, leaf_id(X).
leaf_id_name(X,X) :- not pick_id, leaf_id(X).
leafMap(X,Y) :- leaf_id_name(X,Y), pick_id.


% id of the leaf assigned to be the L^{th} leaf
cspvar(assigned_leaf(L),1,X) :-
	leaf(L),
	num(X).


required(all_different([assigned_leaf/1])).



color(red,0).
color(green,1).
color(blue,2).


cspvar(innerNodeColor(N),0,2) :-
	node(N).



cspvar(weight(N),0,MV) :-
	extnode(N),
	max_total_weight(MV).

required(assigned_leaf(0)==ID -> weight(0)==W) :-
	leaf_id_name(ID,NAME),
	leafWeightCardinality(NAME,W,C).

required((innerNodeColor(N)==GREEN /\ assigned_leaf(N)==ID) ->
		weight(N) == W + C) :-
	node(N),
	color(green,GREEN),
	leaf_id_name(ID,NAME),
	leafWeightCardinality(NAME,W,C).

required((innerNodeColor(N)==RED /\ assigned_leaf(N)==ID) ->
		weight(N) == W + weight(N2)) :-
	node(N), N2 = N-1, extnode(N2),
	color(red,RED),
	leaf_id_name(ID,NAME),
	leafWeightCardinality(NAME,W,C).

required((innerNodeColor(N)==BLUE /\ assigned_leaf(N)==ID) ->
		weight(N) == C + weight(N2)) :-
	node(N), N2 = N-1, extnode(N2),
	color(blue,BLUE),
	leaf_id_name(ID,NAME),
	leafWeightCardinality(NAME,W,C).



% over-constraining
required(assigned_leaf(N)==ID ->
		weight(N) >= min(W + C,
				min(W + weight(N2),C + weight(N2)))) :-
	node(N), N2 = N-1, extnode(N2),
	leaf_id_name(ID,NAME),
	leafWeightCardinality(NAME,W,C).
%
required(assigned_leaf(N)==ID ->
		weight(N) <= max(W + C,
				max(W + weight(N2),C + weight(N2)))) :-
	node(N), N2 = N-1, extnode(N2),
	leaf_id_name(ID,NAME),
	leafWeightCardinality(NAME,W,C).


%
% variable w2 considers weights of "proper" nodes only
% (that is, node 0 is disregarded)
%
cspvar(w2(N),0,MV) :-
	node(N),
	max_total_weight(MV).

required(w2(N)==weight(N)) :-
	node(N).

required(sum([w2/1],<=,MV)) :-
	max_total_weight(MV).


% We can state "exists" as a fact:
% in fact, the program is consistent only 
% if the constraint on total weight
% is satisfied.
exists.




label_order(assigned_leaf(L),1) :-
	leaf(L).

label_order(innerNodeColor(N),2) :-
	node(N).

%label_option(leftmost).
