/*  a file to load the new additions to the CHAT-80 image. */

/* First the Top level controller - exit to sysexit allow prolog to
	invoke a break.  Help not yet changed
*/
runchat :- hi, halt.

control([bye,'.']) :- !,
   display('Cheerio.'),
   nl.
control([prolog, '.']) :- !,
   write('Type \'CTRL Z\' to return to CHAT.'), nl,
   break, fail.
control([trace,'.']) :- !,
   assert(tracing),
   display('Tracing from now on.'), nl, fail.
control([do,not,trace,'.']) :-
   retract(tracing), !,
   display('No longer tracing.'), nl, fail.
control(['help', '.']) :-
    !,
write(
'--- Some special commands --------------------------------\
trace.            (gives some information on the workings)\
do not trace.     (switches it off again)\
bye.              (when you\'ve finished)\
help.             (prints this message)\
\
--- Some questions to try --------------------------------\
What rivers are there?\
Does Afghanistan border China?\
Which countries bordering Spain border France?\
What is the capital of Upper_Volta?\
Where is the largest country?\
which countries are european?\
what country is paris the capital of?\
\n'), fail.

control(U) :-
   process(U),
   fail.


/* Now Jonathan's new reading procedures */

:- prolog_language("pop11").

define iswhite(c);
lvars c;
	strmember(c, '\s\t\r\n')
enddefine;

define isterminator(c);
lvars c;
	strmember(c, '!?.')
enddefine;

define iscloser(w);
lvars w;
	member(w, [. ? !])
enddefine;

vars lastchar;
	false -> lastchar;

define nextcha();
	if lastchar then lastchar; false -> lastchar;
	else cucharin()
	endif
enddefine;

define updaterof nextcha;
	-> lastchar;
enddefine;

define getword();
lvars c item;
	while iswhite(nextcha() ->> c) do /* nothing */ endwhile;
	if isnumbercode(c) then
		c - `0` -> item;
		while isnumbercode(nextcha() ->> c) do
			item * 10 + c - `0` -> item;
		endwhile;
		item
	else
		consstring(uppertolower(c), 1) -> item;
		until iswhite(nextcha() ->> c) or isterminator(c) do
			item >< consstring(uppertolower(c), 1) -> item;
		enduntil;
		consword(item)
	endif;
	c -> nextcha();
enddefine;

define readin();
vars popprompt;
	'' -> popprompt;
	[%
	until iscloser(dup(getword())) do /* nothing */ enduntil;
	%]
enddefine;

define prolog_interrupt;
vars prolog_interrupt;
	if iscaller(prolog_invoke) then
		false -> prolog_interrupt;			;;; disable;
		sysflush(popdeverr);
		sysflush(popdevout);
		if systrmdev(popdevraw) then sysflush(popdevraw) endif;
		pr('\nCHAT-80\n');
		prolog_maketerm("runchat", 0);
		chainfrom(prolog_invoke, prolog_invoke);
	endif;
enddefine;

:- prolog_language("prolog").
