d processes
:- ['./data/junction.db']. % load junctions

:- ['./data/init.db'].    % initial state info 
:- ['./data/trigger.db']. % load triggers

:- [library].

% , store,conflict,cond,exe,model]. % load prolog files 

% data files 

% :-  ['./data/cond.db']. 

% :-  ['./data/dyn.db'], ['./data/entity.db'],['./data/process.db'],
%     ['./data/trigger.db']. 

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

:- write('**********************************************************'),nl,
   write('Welcome to The Business Model Simulator for FBPML'),nl,
   write('This simulator is a part of the tool KBST-BM.'), nl,
   write('If you want to run one step at a time, type run. '), nl, 
   write('To run several steps at a time, type top(X). '),nl,
   write('Where X is the number of steps required for enactment.'),nl,
   write('At the end of the enactment type look. to see results.'),nl,   
   write('**********************************************************'),
   nl, nl.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% top(+Step)
% Top Rule for dynamic model reasoning/simulation
% When called, the simulator will run a specified number of Steps.
%
% operates at time and states level
% export_data_to_archive is given in store.pl 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

run :-  top(1). 

%% (1) end of enactment 
top(Step) :-
    Step =< 0, 
    dyn(current_time(Time)),
    write('* End of enactment'),nl, 
    W is Time - 1, 
    write('* Enactment stops at the end of time: '), write(W),nl,
    export_data_to_archive, !. % store.pl 

%% (2) find matching processes 
top(Step) :-
    Step > 0,
    \+     dyn(flag(done_matching))), 
    assert(dyn(flag(done_matchine))), 
    meta_match_process,
    top(Step).

%% (3) execute processes
top(Step) :-
    Step > 0,
    \+     dyn(flag(done_execution)), 
    assert(dyn(flag(done_execution))), 
    meta_exec_process, 
    top(Step).

%% (4) update time and state_id, and get new triggers

top(Step) :-
    dyn(flag(done_matching))), 
    dyn(flag(done_execution))), 

    Step > 0,
    Current_step is Step - 1,
    
    % update time
    dyn(current_time(Time)),
    Newtime is Time + 1,
    retract(dyn(current_time(Time))),
    assert(dyn(current_time(Newtime))),

    % If any changes are made to the state, update state.
    % Otherwise, do not. 

    (          dyn(flag(state_changed)), 
       retract(dyn(flag(state_changed)), 
       update_state;  
       true
    ),

    write('* Finish one enactment step/time unit. '), nl, 
    write('* Enactment time ends at: '), write(Time),nl, 
    write('* Enactment steps left: '), write(Current_step),nl, 
  
%   query_for_adding_triggers,
    top(Current_step). 

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%