/*  ATNI.PL  */


:- reconsult( 'atncommon.pl' ).


do_node( fail ) :-
    !, fail.

do_node( succeed ) :- !.

do_node( A ) :-
    '$node_command'( A, Command ),
    call( Command ),
    !,
    '$node_arc'( A, Cond, Next ),
    call( Cond ),
    !,
    do_node( Next ).


retract_expanded_atn( atn(Node,Command,Arcs) ) :-
    retractall( '$node_command'(Node,_) ),
    retractall( '$node_arc'(Node,_,_) ).


assert_expanded_atn( atn(Node,Command,Arcs) ) :-
    atn_to_facts( Node, Command, Arcs, Facts ),
    assert_nodes( Facts ).


atn_to_facts( Node, Command, Arcs, [F1|ArcFacts] ) :-
    F1 = '$node_command'( Node, Command ),
    arcs_to_facts( Node, Arcs, ArcFacts ).


arcs_to_facts( _, [], [] ) :- !.

arcs_to_facts( Node,
               [true,Next|_],
               ['$node_arc'(Node,true,Next)] ) :- !.

arcs_to_facts( Node,
               [Cond,Next|Rest],
               ['$node_arc'(Node,Cond,Next)|RestFacts] ) :-
    !,
    arcs_to_facts( Node, Rest, RestFacts ).


assert_nodes( [] ) :- !.

assert_nodes( [F|Rest] ) :-
    assert( F ),
    assert_nodes( Rest ).
