run_clingo(File,MaxNrModels,TimeoutSecs,WT,Result,Exhaustive) :-
statistics(walltime,[Start,_]),
(debug_mode(on) -> DOpt=['-V'] ; DOpt=[]),
(MaxNrModels<2 -> ModelsOpt='--models=1' % so that code works without ajoin
; ajoin(['--models=',MaxNrModels],ModelsOpt)),
(TimeoutSecs >= 0
-> ajoin(['--time-limit=',TimeoutSecs],TimeOpt), TOpt = [TimeOpt|DOpt]
; TOpt=DOpt),
OtherOptions = [ModelsOpt|TOpt] , % =0 outputs all models
debug_format(19,' Running CLINGO on ~w (options=~w)~n',[File,OtherOptions]),flush_output,
Options = [process(Process),stdout(pipe(JStdout,[encoding(utf8)])),
stderr(pipe(JStderr,[encoding(utf8)]))],
(get_clingo_path(Clingo), file_exists(Clingo)-> true
; get_clingo_path(Clingo) -> add_b2asp_error('Cannot find Clingo binary at (be sure to set path_to_clingo preference to point to clingo binary): ',Clingo),fail
; add_b2asp_error('Cannot find Clingo binary (be sure to set path_to_clingo preference to point to clingo binary)',''),fail
),
safe_process_create(Clingo, [File|OtherOptions], Options),
debug_format(4,' Created process ~w~n',[Options]),flush_output,
read_all(JStdout,Clingo,stdout,OutLines), % read before process_wait; avoid blocking clingo
read_all(JStderr,Clingo,stderr,ErrLines),
debug_format(4,' process_wait ~w~n',[Process]),flush_output,
process_wait(Process,Exit),
% above almost corresponds to: system_call_with_options(Clingo,[File|OtherOptions],[],OutLines,ErrLines,ExitCode)
% except that here we do not call append/2 on OutLines and ErrLines
statistics(walltime,[Stop,_]), WT is Stop-Start,
format(' CLINGO walltime: ~w ms, ~w~n',[WT,Exit]),flush_output,
debug_format(19,'--- CLINGO OUTPUT ----~n',[]),flush_output,
start_ms_timer(T1),
process_clingo_output(OutLines,Models),
get_elapsed_walltime(T1,WT1),add_to_profile_stats(back_translation_time,WT1),
stop_ms_timer_with_msg(T1,'translating clingo model back to B'),
if((Exit=exit(Code),
% ErrLines = [], % clingo write debug info on stderr (parsed program, rewritten program)
translate_clingo_exit_code(Code,Models,Result,Exhaustive)
),
(debug_format(19,'Clingo exit code = ~w -> ~w (~w)~n',[Code,Result,Exhaustive]),
show_stderr(ErrLines)),
(format('Unrecognised exit code: ~w~n',[Exit]),
show_stderr(ErrLines),
Result=no_solution_found(Exit))
).