:- eval(ex016()).

ex016() :-
	SB = StringBuffer(":- foobar(toto(1)).:- eval(toto(2))."),
	on_exception(ws.prova.parser.ParsingException,on_parsing_errors(Filename)),
	% this is asynchronous but...
	consult(XID,SB),		% NOTE, XID must be free before this call
	println(["Consulted: ",SB]),
	% ...we can intercept here all messages resulting from the consult above.
	% Note that the "eval" goal is not intercepted and
	%    results in regular goal submission 
	rcvMult(XID,self,From,Perf,[X|Xs]),
	println(["Message ",Perf,[X|Xs]," received."]),
	% ...and dispatch each goal according to its pattern
	%    together with XID in case we need it.
	run_goal(XID,Perf,[X|Xs]).

% All user goals can be processed in rules for 'run_goal' so we get control 
% over backtracking. XID is equal to that of the original consult above.
run_goal(XID,foobar,[X|Xs]) :-
	derive([X|Xs]),
	% A test that succeeds once the further replies are not needed
	until([X|Xs]),
	!.

% A testing harness for printing incoming end_of_transmission messages.
% This message is sent last from the conversational consult to   
rcvMsg(XID,Protocol,From,end_of_transmission|Extra) :-
	println(["end_of_transmission for conversation-id ",XID,": "|Extra]).

toto(I) :-
	println(["toto[1]=",I]).
toto(I) :-
	println(["toto[2]=",I]).

until(toto(1)).

on_parsing_errors() :-
	exception(Ex),
	Ex.printStackTrace(),
	fail().
