:- module(cmdline,[get_command_line/2]).

%
% detect Quintus/SICStus/ECLiPSe/SWI
%

:- [prolog_detect].

:- prolog_detect:prolog(Prolog),
	(	(Prolog=sicstus,
		use_module(library(system))		%load the system module for SICStus
		);
		(Prolog=pfdm,
		use_module(library(system))		%load the system module for SICStus
		);
		(Prolog=swi,
		use_module(library(quintus))		%load the quintus module for SWI
		);
		true					%no need for Quintus
	).


get_command_line(Arg_name,Arg_value) :-
	prolog_detect:prolog(Prolog),
	get_all_args(Prolog,Args),
	match_arg(Args,Arg_name,Value_as_atom),
	atom_to_value(Value_as_atom,Arg_value).

atom_to_value(Atom,Value) :-
	name(Atom,String),
	name(Value,String).


match_arg([Arg,Value|_],Arg,Value).
match_arg([_,_|Rest],Arg,Value) :-
	match_arg(Rest,Arg,Value).


%
% collect all args into a list (in the correct order)
%

%
% for Quintus
%
get_all_args(quintus,Args) :-
	unix(argv(Args)).

%
% for SICStus
%
get_all_args(sicstus,Args) :-
	prolog_flag(argv,Args).

%
% for SWI
%
get_all_args(swi,Args) :-
	unix(argv(All_args)),	%get all args in a list (Quintus compatible)
	chop(All_args,Args).	%chop out those before '--'

%
% for ECLiPSe
%
% NOTE:	There is a bug in ECLiPSe where '--' is chopping out
%	arguments to ECLiPSe and leaving the rest to the Prolog program.
%	However, "argc" is not properly adjusted. Thus "argc(N)" still
%	gives the total no. of args but args before '--' are replaced
%	by those after '--'. Some args are being duplicated by this bug.
%
get_all_args(eclipse,Args) :-
	argc(N),				%get the no. of args
	get_all_args(eclipse,N,[],Args).	%get all args in a list


get_all_args(eclipse,1,Args,Args) :-
	!.

get_all_args(eclipse,N,So_far,Args) :-
	M is N-1,
	M>=0,
	argv(M,Arg_in_string),					%get argument no. M
	name(Arg_in_string,Char_list),				%ECLiPSe returns a string, so we have to convert it to an atom
	name(Arg_in_atom,Char_list),
	get_all_args(eclipse,M,[Arg_in_atom|So_far],Args).

%
% chop away arguments before '--' for SWI
%
chop([],[]).

chop(['--'|Args],Args) :-
	!.
chop([_|All_args],Args) :-
	chop(All_args,Args).

