#!/usr/bin/pl -q -t main -f

:- op(500, fx, #).

canonicalize(File) :-
	open(File, read, Stream),
	( repeat,
	  read_term(Stream, Term, [double_quotes(atom)]),
	  ( Term == end_of_file ->
	    !,
	    close(Stream)
	  ; write_term(Term, [quoted(true),ignore_ops(true),portray(true)]),
	    writeln('.'),
	    fail
	  )
	  ; true
	).

canonicalize_argv :-
	current_prolog_flag(argv, Argv), 
	append(_, [--|Args], Argv),
	!,
	concat_atom(Args, ' ', SingleArg),  
	canonicalize(SingleArg).

main :-
	fix_ops,
        catch(canonicalize_argv, E, (print_message(error, E), fail)),
        halt.                                           
main :-
        halt(1).

%%%%  
%%%% SWI-prolog prints operators >= 1000 in brackets (also if
%%%% ignore_ops is true). portray is used here to patch this.
%%%%  
fix_ops :-
	findall(O, (current_op(P,_,O), P >= 1000), Os),
	sort(Os, Os1),
	( member(O1, Os1),
	  asserta(portray(O1) :- write_term(O1, [quoted(true)])),
	  fail
	; true
	).
