%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                           %
%       file:           head.pl                                             %
%       purpose:        semantic-head-driven generation                     %
%       author:         Sebastian Varges                                    %
%       date:           Tue Feb  4 12:35:37 MET 1997                        %
%       related files:  memo_head.pl, top.pl, grammar.pl                    %
%                                                                           %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

head_proc(Root) :-
        head_link(Root,Pivot),  
        nonchain_rule(Pivot,N,RuleType),
        instantiate_nonchain_rule(RuleType,N,Pivot,RHS),
        head_proc_rhs(RHS),
        connect_up(Pivot,Root).

instantiate_nonchain_rule(lex,N,Pivot,[]) :-    %  lexical entry
        node(N,Pivot). 

instantiate_nonchain_rule(rule,N,Pivot,RHS) :-  % grammar rule       
        (node(N,Pivot) <--- RHS).

head_proc_rhs([]).          
head_proc_rhs([node(F)|R]) :- 
        head_proc(F),
        head_proc_rhs(R).
        
connect_up(Pivot,Pivot).
connect_up(Pivot,Root) :-
        head_link(Root,Pivot),
        chain_rule(NewPivot,N,RuleType),
        instantiate_chain_rule(RuleType,N,Pivot,NewPivot,RedRHS),
        head_proc_rhs(RedRHS),
        connect_up(NewPivot,Root).

instantiate_chain_rule(unary,N,Pivot,NewPivot,[]) :-
        (node(N,NewPivot) <--- [node(Pivot)]).

instantiate_chain_rule(left,N,Pivot,NewPivot,[node(Left)]) :-
        (node(N,NewPivot) <--- [node(Left),node(Pivot)]).

instantiate_chain_rule(right,N,Pivot,NewPivot,[node(Right)]) :-
        (node(N,NewPivot) <--- [node(Pivot),node(Right)]).