/*
 * This file contains two predicates
 *   - read_and_just_print_roads/1
 *   - read_and_return/3
 * that illustrate reading one line at a time from a file in SWI Prolog.
 * The file has the format of input files of the 'dromoi' exercise.
 */

/*
 * The first predicate is not so interesting. It just shows you how you can
 * write in Prolog a predicate that contains a loop with *only* side-effects.
 * Use as:
 *
 *   ?- read_and_just_print_codes('anaptyksi1.txt').
 */
read_and_just_print_codes(File) :-
    open(File, read, Stream),
    repeat,
    read_line_to_codes(Stream, X),
    ( X \== end_of_file -> writeln(X), fail ; close(Stream), ! ).

/*
 * The second predicate reads the information of an input file and returns
 * it in the next three arguments: two integers and a list with seg/2
 * structures with the start and end of a segment, as in the example below:
 * 
 *   ?- read_and_return('anaptyksi1.txt', L, X, Segs).
 *   L = 30,
 *   X = 6,
 *   Segs = [seg(1, 5), seg(11, 27), seg(2, 14), seg(18, 28)].
 *
 * To read the information of each of the segments, it uses the auxiliary
 * predicate read_segs/3.
 */

read_and_return(File, L, X, Segs) :-
    open(File, read, Stream),
    read_line(Stream, [N, L, X]),
    read_segs(Stream, N, Segs),
    close(Stream).

read_segs(Stream, N, Segs) :-
    ( N > 0 ->
	Segs = [Seg|Rest],
        read_line(Stream, [S, E]),
	Seg = seg(S, E),
        N1 is N - 1,
        read_segs(Stream, N1, Rest)
    ; N =:= 0 ->
	Segs = []
    ).

/*
 * An auxiliary predicate that reads a line and returns the list of
 * integers that the line contains.
 */
read_line(Stream, List) :-
    read_line_to_codes(Stream, Line),
    atom_codes(A, Line),
    atomic_list_concat(As, ' ', A),
    maplist(atom_number, As, List).
