% Prova 1.9 bug corrections.
% Some uses of various builtins like "concat" with bound result passed as the last argument.
% The example also recaps the use of various string manipulation builtins.

:- eval(p()).

p() :- 
	concat([a,b], AB),
	println(["1: ",AB]), 
	concat([a,c], AC), 
	println(["1: ",AC]), 
	concat([a,c], AB), 
	% This line is (correctly) unreachable in Prova 1.9
	println(["1: ",AB," = ",AC]).
p() :-
	% Create a list of tokens separated by ","
	tokenize_list("a,b,c",",",[T|Ts]),
   println(["2: ",[T|Ts]]).
p() :-
	% The following would have (incorrectly) unified before Prova 1.9 
	tokenize_list("a,b,c",",",ttt),
   println(["3: ",ttt]," ").
p() :-
	% Enumerate tokens separated by "," non-deterministically
	tokenize_enum("a,b,c",",",X),
   println(["4: ",X]).
p() :-
	tokenize_enum("g,g,g",",",g),
   println(["5: ",g]).
p() :-
	parse_list("abc:-12a234","(?:(\w*):|)(-?\d*\w?)-?(\d*)",[T|Ts]),
   println(["6: ",[T|Ts]]).
p() :-
	% The following would have (incorrectly) unified before Prova 1.9 
	parse_list("abc:-12a234","(?:(\w*):|)(-?\d*\w?)-?(\d*)",ttt),
   println(["7: ",ttt]," ").
p() :-
	% Non-deterministically enumerate regular expression groups
	capture_enum("A doodle is a doddle","(d?)(dl)",Groups),
   println(["8: ",Groups]).
p() :-
	% Non-deterministically enumerate regular expression groups
	capture_enum("A doodle is a doddle","(d?)(dl)",[X,"dl"]),
   println(["9: ",[X,"dl"]]).
p() :-
	% The following would have (incorrectly) unified before Prova 1.9 
	capture_enum("A doodle is a doddle","(d?)(dl)","dl"),
   println(["10: dl"]).
p() :- 
   on_exception(java.io.IOException,on_io_exception(Reader)),
   fopen("nosuchfile.xml",Reader),
   % Enumerate and print one Line at a time
   read_enum(Reader,Line),
   println(["11: ",Line]).
p() :- 
   on_exception(java.io.IOException,on_io_exception(Reader)),
   fopen("nosuchfile.xml",Reader),
   % Enumerate and print one Line at a time
	% The following would have (incorrectly) unified before Prova 1.9
	% The code below checks that all the lines in a file are equal to "ttt", which is not true.
   read_enum(Reader,ttt), 
   println(["12: ",ttt]).
p() :- 
	% The following would have (incorrectly) unified before Prova 1.9
	% Note that "f" is a constant string that plainly cannot match a returned File object 
   fopen("ra007.prova",f),
   println(["13: ",ttt]).

on_io_exception(Reader) :-
   exception(Ex),
   % Corrective action: make Reader access a constant String
	unescape("Line 1\rLine 2\rLine 3",Unescaped),
   StringReader=java.io.StringReader(Unescaped),
	Reader = java.io.BufferedReader(StringReader).

:- solve(aaa(X)).

% No problems here
aaa("aaaa\x"
).

% This prints:
% 1: ab
% 1: ac
% 2: ["a","b","c"]
% 4: a
% 4: b
% 4: c
% 5: g
% 6: ["abc","-12a","234"]
% 8: ["","dl"]
% 8: ["d","dl"]
% 9: ["","dl"]
% 9: ["d","dl"]
% 11: Line 1
% 11: Lin 2
% 11: Line 3
% X="aaaa\x"
