% top level file, loads the grammar file ('program42-mod2.pl') and
% BB's model checker ('modelChecker2.pl'); presupposes the presence in the same
% directory of 'exampleModels.pl' with a model number 1 that uses the logical
% expressions of the grammar of English in 'program42-mod2.pl'

% needs slight adaptation for printing the logical representations to Prolog shell
% calling BB's model checker, etc. (add the relevant code from the SICStus version)


%% A program to help you test your grammar. Works on SWI-Prolog
%% but can be easily adapted for other systems (the process
%% startup and I/O might have to be changed). Written by Martin Lazarov

% load the default test grammar and the parser
:- [program42-mod2], [modelChecker2].

%
% test/0 repeatedly reads sentences from stdin, and parses
% them, retrieving all parse trees, which are then send to a tree viewer.
% The tree viewer is a Java program that reads trees, encoded as LISP
% S-expressions, from its input stream and displays them.
%
parse :-
    % uncomment to see what's being sent to the tree viewer
    %current_output(StdOut),
    StdOut=treg,    % an alias of the tree viewer's input stream
    repeat,
        readln(S),
        
        % initialize the tree counter
        retractall(tree_cnt_(_)), assert(tree_cnt_(0)),
        
        % retrieve all parse trees, incrementing the tree
        % counter on each
        findall(_,
            (parse(S,T), show_tree(StdOut,T), inc_tree_count),_),
        
        nl,
        fail.

%
% Increments the global tree counter. The counter is reset
% before each sentence is parsed.
%
inc_tree_count :-
    tree_cnt_(X),
    retractall(tree_cnt_(_)),
    X1 is X + 1,
    assert(tree_cnt_(X1)),
    write(X1), write(' '), !.

%
% Sends a tree to the tree viewer.
%
show_tree(Tree) :- show_tree(treg,Tree).
show_tree(Stream,Tree) :-
  % open the stream if necessary
  (
  \+is_stream(Stream) -> open(
      pipe('java -jar tv.jar'),write,_,
      [buffer(false),alias(Stream),encoding(octet)]
      )
  ;
  true
  ),
  
  % send the window's title
  write(Stream, Tree), nl(Stream),
  
  % send the tree
  print_tree(Stream,Tree), nl(Stream).


%
% print_tree/2 writes a tree represented as a Prolog term to
% the tree viewer's input stream in its format.
%

% leaf case
print_tree(Stream,Leaf) :-
    functor(Leaf,_,0), !,
    write(Stream, '("'),
    write(Stream, Leaf),
    write(Stream, '" [style=bolditalic color=blue])').

% internal node case
print_tree(Stream,Tree) :-
    functor(Tree,Root,Arr),
    write(Stream, '("'),
    write(Stream, Root),
    write(Stream, '" [style=bold]'),
    print_args(Stream,Tree,0,Arr),
    write(Stream, ')').

print_args(_,_,N,N) :- !.
print_args(Stream,Tree,I,N) :-
    I1 is I+1,
    arg(I1,Tree,Arg),
    print_tree(Stream,Arg), 
    print_args(Stream,Tree,I1,N).
