tally :-
    retractall(word(_,_)),
    repeat,
        readline(Line),
        do_line(Line),
        Line == '', !,
        show_counts.

readline(Line) :-
    read_line_to_codes(user_input, Codes),
	atom_codes(Line, Codes).

do_line('').
do_line(Line) :-
        concat_atom(Words, ' ', Line), % splits Line on blanks
        member(Word, Words),
        count(Word), fail.
do_line(_).

count(Word) :-
    word(Word,Count0),
	retract(word(Word,_)),
	Count is Count0+1,
	assert(word(Word,Count)), !.
count(Word) :- assert(word(Word,1)).

show_counts :-
    writeln('\n-- Results --'),
	findall(W-C, word(W,C), Pairs),
	keysort(Pairs, Sorted),
    member(W-C, Sorted),
	format('~w~t~12|~w~n', [W,C]),
	fail.
show_counts.    

