/* PROCEDURES TO MANAGE THE AGENDA */

/* The agenda is represented using the PROLOG internal data base
   predicates.  A task for a given priority P is recorded using
   P as its key.  The global variable "max_priority" holds the highest
   priority of all the current tasks.  The purpose of the kludgery is
   to prevent a recursive call each time a task is run. */


run :-
   repeat,
   get_task(Task),
   do(Task),
   fail.


get_task(Task) :-
   flag(max_priority,P,P),
   recorded(P,Task,ID),
   erase(ID),
   !.

get_task(nothing) :-
   flag(max_priority,0,0),
   !.

get_task(Task) :-
   flag(max_priority,P,P),
   P1 is P-1,
   flag(max_priority,_,P1),
   get_task(Task),
   !.



add_task(Task) :-
   trace('adding task %t to agenda\n',[Task],3),
   priority(Task,P),
   recordz(P,Task,_),
   new_priority(P).



new_priority(P) :-
   flag(max_priority,M,M),
   P > M, !,
   trace('changing max priority to %t\n',[P],3),
   flag(max_priority,_,P).

new_priority(P) :- !.
