%
% prim_fakt/2
% naive algorithm to calulate prime faktors for positive numbers
%
prim_fakt(Number, Factors) :-
    prim_fakt(Number,2,Factors).

prim_fakt(Number,N,Number) :- 
    N >= Number, !.
prim_fakt(Number,N,Factors) :- 
    Number mod N > 0, !, 
    N1 is N+1,   
    prim_fakt(Number,N1,Factors).
prim_fakt(Number,N,Factors*N) :- 
    Number1 is Number//N,
    prim_fakt(Number1,N,Factors).


%
% build the widget Tree and map it to the screen

init :-
    xui( ['Form top topLevel ',
	    'Text input top editType edit width 200',
	    'action input override {<Key>Return: exec(echo \"[gV input string]\" .)}',
	    'Label result top label {} width 200 fromVert input',
	    'Command quit top fromVert result callback quit',
	    'Label info top fromVert result fromHoriz quit label {} borderWidth 0 width 150',
	    'realize'
	      ]),
    get_input(X), 
    command_interpreter(X).

%
% toplevel Command interpreter

command_interpreter(halt). 
command_interpreter(Input) :- 
    handle_input(Input),
    get_input(Next), 
    command_interpreter(Next).

%
% insert your favourite read-line package here.

get_input(Input) :-
    read(List),
    name(Input,List).

%
% do the real work here

handle_input(Input) :- 
    number(Input), !,
    format("%sV info label {thinking ...}~n",[]), ttyflush,
    time_it(prim_fakt(Input,2,Faktors),Ms),
    format("%sV info label {~w milliseconds}~n%sV result label {~w}~n",[Ms,Faktors]),
    ttyflush.
handle_input(_) :- 	    
    format("%sV info label {not an numeric value}~n",[]),
    ttyflush.

%
% utility predicates

xui([]) :- ttyflush.
xui([H|T]) :- write('%'), write(H), nl, xui(T).    

time_it(Goal,Diff) :-
        statistics(runtime,[T1,_]),  Goal,  statistics(runtime,[T2,_]),
        Diff is T2 - T1.





