/*
    This file is part of SUPPL - the supplemental library for DOS
    Copyright (C) 1996-2000 Steffen Kaiser

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/* $Id: CFG.H 1.9 2001/02/27 01:29:31 ska Exp ska $
   $Locker: ska $	$Name:  $	$State: Exp $

	Declarations for the option scanning system

	This set of functions is intend to unify the way options and
	arguments are scanned from command line and additionally sources, such
	as environment variables, configuration files and INI files.

	The strings within environment variables and configuration files are
	interpreted like command line options with the exception that they are
	broken into arguments by this function rather by the startup code of the
	program. Therefore the term "configuration file" will be applied to
	INI files and "command line" refers to all other sources in the future,
	unless noted otherwise.

	"short name of options": is an (int) value internally representing 
		an option. The value 0 (zeto) is reserved for error conditions.
		The values 1..0xff are reserved for options that can appear as
		single-character options on the command line.
		The values 0xff80..0xffff as well, because some compilers use
		a signed (char) type.

		Every option used by a program must have a shortname.

	"long name of options": is an (char*) value that refers to a string
		that is associated to a shortname option. (see struct Cfg_LongOptions).
		Longnames can appear as "long options" on the command line or as
		"value names" in configuration files. To avoid confusion, longnames
		should be constructed out of the characterset [a-zA-Z0-9\-\_\ ],
		where the dash '-', the underscore '_' and the blank ' ' match
		themselves equally; longnames must start with a letter [a-zA-Z] and
		end with an alphanumeric character [a-zA-Z0-9].

		To process longname options they are translated into the associated
		shortname option.


	The process to scan options shall work with less help from the user.
	The recommended way to process options is to let the command line
	scanner aquire the next option with its arguments, if present, then
	a function is called which contains an huge switch() statement to
	associate the option with the proper type, whether or not it can use
	an argument, and whether or not the argument can be delimited by an
	in-argument option character, and the user calls the proper function(s)
	to handle the case and passes the proper address to the variable that
	shall recieve the data.

	Command line options:
	A command line may look like this:

		        1   2     3   4  5   6           7     8         9
		command /mdf/msg=1/+qf/vv/i-m/i="foo bar"/d=foo/e=65 arg1/opt27

	This command line shall be interpreted as following:
		1) Single-character options: 'm', 'd', 'f', 'q', 'v', 'i'
		2) Longname options: 'msg', 'opt27'

		The 1st '/' is an option sign. Theoretically this can be any
		character, however, one should stick to '/' or '-'.
		This character indicates that the first argument on the command line
		is an option indeed.

		The 'mdf' is a string of three individual single-character options
		that directly corresponse to the shortname options 'm', 'd', and 'f'.
		If the "non-argumented type" of these options is defined, they
		will act following:
			boolean --> toggle --> cfg_i = !cfg_i
			integer --> increment --> ++cfg_i
			string --> clear --> cfg_s = NULL

		The 2nd, 3rd, ..., 7th '/' must be an in-option option sign.
		For convinance with the traditional command lines this should be
		the forward slash '/' only.

		The 'msg=1' string is interpreted as an argumented longname option.

		The '+qf' is a string of a global boolean switch ('+' at first
		position) and two individual single-character options.
		Depending on the type of 'q' and 'f' they perform:
			boolean --> set --> cfg_i = 1
			integer --> set --> cfg_i = 1
			string --> clear --> cfg_s = NULL

		The 'vv' is similar to 'mdf'. However due to the multiple appearance of
		the option the result is:
			boolean --> 2 * toggle --> cfg_i = !!cfg_i (This does no change the
						boolean meaning of cfg_i, but modifies cfg_i, if it
						was neither 0 nor 1)
			integer --> 2 * increment --> cfg_i += 2
			string --> 2 * clear --> cfg_s = NULL

   		'i-m', under the prerequisite that '-' is no in-option option
   		sign, but a boolean sign, this string splits into the two
   		options: "/-i" and "/m". However, I personally would prefer to
   		interprete it like "/i/-m" but the FreeDOS community seemed to
   		disagree in past. The "/-i" would be interpreted as:
   			boolean --> clear --> cfg_i = 0
   			integer --> clear --> cfg_i = 0
   			string --> clear --> cfg_s = NULL

   		'i="foo bar"' arguments can be enclosed into quotes (at least one
   		quote is to be available: the double quotes), if an in-option option
   		sign immediately follows the closing quote, it is interpreted
   		as an option delimiter.
   		Depending on the type of 'I' the result is:
   			boolean --> error
   			integer --> error
   			string --> assign --> cfg_s = "foo bar"

		"d=foo/e=65" is an assignment of 'foo/e=65' to the option 'd', unless
		the 8th '/' is an in-argument option sign and the 'd' option calls
		"cfgBrkArg()". In that case, "/e=65" would be an option of it's own.

		"arg1/opt27" is a non-option argument, because it does not start
		with an option sign. However, if the 9th '/' is an in-argument
		option sign, the non-option argument would be reduced to "arg1"
		and "/opt27" would be interpreted as an option and would match the
		longname option 'opt27'.

	The three different "option signs":
		"normal": if the first character of an argument of a broken up
			command line is an option sign, the whole argument is processed
			as one or more options. Otherwise the argument is a non-option
			argument.
			Traditionally this is the forward slash '/' only. To support the
			specific DOS API it is the "switch character". Unix-fans would
			love to use the dash '-' as well.
			Current implementated defaults (first available used):
				1) the value of the environment variable SWITCHAR,
					the whole string except whitespaces
				2) global configuration settings
				3) DOS API DOS-37-00 Get Switchar, this single character only
				4) the forward slash only

		in-option: These characters delimit a second option from another one.
			These characters are recognized only:
				+ if the first (left / leading) option has no argument, or
				+ the argument is fully enclosed into quotes and the sign
					immediately follows the closing quote.

			Current implementation defaults:
				If the "normal" option sign contains the forward slash,
				the forward slash is used, otherwise nothing (hence, disabling
				this feature).  
		in-argument: These characters delimit a second option from any
			argument (option or non-option or argumented option).
			These signs are recognized only:
				+ if not quoted.

			Current implementation defaults:
				The same as "in-option" signs.

		How to disable combinations of single-character options:
			Define longname options for each single-character option and
			give them a shortname greater than 255.

	Response files

	The DOS convention allows a maximum of 253 characters to be passed as
	"command line arguments" to a program. This limit does not show up
	that often when processing commands an user typed in interactively,
	but when processing batch jobs or an automatical generated file list
	or when the program is traditional unable to glob wildcards (e.g.
	the DOS librarian) a.s.o.

	Response files are passed as normal command line arguments to the
	program, which actively opens the files and tread their content as
	if typed on command line, e.g.:
	|=== File: file.rsp
	|/option1 argument1
	|argument2/option2

	If the command line looks like this and the way to identify response
	files is to prefix a normal non-option argument by '@':
	C:\> program /optA argA argB @file.rsp argC/optB

	The program would recieve (in that order) the following options/arguments:
	/optA
	argA
	argB
	/option1
	argument1
	argument2
	/option2
	argC
	/optB

	The "@file.rsp" is silently replaced by the content of the file.

	One requirement for response files is the limit of the command line.
	However, one can find more uses for them, for instance you can
	generate the command line (e.g. in batch files) for a command into
	a temporary file or you can easily pass the output of other programs
	as command line arguments to another program and, in contrast to
	standard ".BAT" files, the generator need not worry about the length
	and/or the mass of delimiters (whitespaces, newline characters) a.s.o.

	When _all_ commands accept response files, the user would probably
	find even more useful useages for them, even the shell could pass
	all the arguments within a response file, thus, allow a theoretically
	unlimited length of the command line.
	If the response file is a device (e.g. the keyboard), one can even
	play some interesting tricks.

	The current implementation accepts exactly one customizeble character
	as the prefix, but accepts nested and/or multiple response files.

	Because there are response files that could be extremly huge, but
	impossible to re-read, e.g. pipes (even if the current
	implementation uses temporary files, this is not sure) or when the
	file is read from the keyboard, response files are cached into a
	temporary file in some circumstances. Note: This applies to information
	from the response file(s) only.

	Response files are opened in read-only text mode.

*/

#ifndef __CFG_H
#define __CFG_H

#include <portable.h>
#include "cfg_base.h"

/*
 * States the cfgGetopt() function can be in
 */
#define CFG_UNINITIALIZED 0	/* never used getopt() on this buffer */
#define CFG_ARG 1		/* non-option argument */
#define CFG_OPT	2		/* option */
#define CFG_EOF 3		/* no more arguments */
#define CFG_NONE 4		/* no pending argument --> must be aquired or
							judged by the other values of the buffer */

/* 
 * Commands & flags how to update string options
 */
/* one of the following */
#define CFG_OPT_PREPEND		1		/* prepend by default */
#define CFG_OPT_APPEND		2		/* append by default */
#define CFG_OPT_OVERWRITE	3		/* replace the current value */
/* Can be ORed if applicable */
#define CFG_OPT_HONOR_SIGN	8		/* ignore '+'/'-' to alter default */


/*
 *	The type of values for shortname options is (int).
 *	From this set the following have special purposes:
 *		0x01..0xff:	The shortname option with the respective ASCII value
 *		~0..(~0-0x7f): The shortname options 0x80..0xff, if (char) is
 *			signed.
 *		0:		no option found
 *		(~0-0x80)..(~0-0xff): special meaning / internal useage (see below)
 */
#define CFG_CHR_NONE		0					/* no option found */
#define CFG_CHR_UNKNOWN		((int)(~0-0x80))	/* unknown longname opt */
#define CFG_CHR_RESCAN		((int)(~0-0x81))	/* internal: continue scan
													process */

/*
 *	How to define/declare a function that interpretes options
 *	This function is to be called:
 *		<name>(<getopt_structure>)
 */
#define Cfg_FctInterprete(name)	void name(struct Cfg_Getopt * const optstru)

/*
 *	Longname option support
 */
struct Cfg_LongOptions {
	int shortname;		/* short name of option */
	char *longname;		/* long name of option */
};
#ifdef _MICROC_
#define CFG_LOPTENTRY(lopt,sopt)	int (lopt), (sopt)
#else
#define CFG_LOPTENTRY(lopt,sopt)	{ (lopt), (sopt) }
#endif

/*
 *	How to define a function suitable for getopt()
 *
 *	Cfg_rdTokFct: Scans the next token (option/argument) from the 
 *		input stack item and sets all necessary values in optstru
 *		as to satisfy cfgGetopt()
 *	Cfg_rdOptFct: Returns the next character from an input stack item
 *		Returns EOF on failure (for cfg_getStream() only)
 *	Cfg_clOptFct: Closes an input stack item
 *	Cfg_wrArgFct: Inserts an argument into the output stack item
 *	Cfg_rdArgFct: Returns a specific argument from this ostack item
 *		Returns NULL on failure (index not in range)
 *	Cfg_sqArgFct: Sequential read, removes the returned string the next
 *		time, if _removeAfterRead is enabled
 *		Return NULL on failure (index not in range)
 *	Cfg_clArgFct: Close this output stack item
 *	Cfg_get<type>Fct: Return the data of the current option in the
 *		native format.
 */
#ifdef _MICROC_
#define Cfg_FctGetopt int
#define Cfg_rdTokFct int
#define Cfg_rdOptFct int
#define Cfg_clOptFct int
#define Cfg_wrArgFct int
#define Cfg_rdArgFct int
#define Cfg_sqArgFct int
#define Cfg_clArgFct int
#define Cfg_ostkEnum int
#define Cfg_getIntegerFct int
#define Cfg_getBooleanFct int
#define Cfg_getStringFct int
#else
typedef int (*Cfg_FctGetopt)(struct Cfg_Getopt * const);
typedef int (*Cfg_rdTokFct)(struct Cfg_Getopt * const);
typedef int (*Cfg_rdOptFct)(struct Cfg_Getopt * const);
typedef void (*Cfg_clOptFct)(struct Cfg_Getopt * const);
typedef void (*Cfg_wrArgFct)(int, struct Cfg_Getopt * const
	, struct Cfg_oStackGetopt * const , char * const, size_t);
typedef char * (*Cfg_rdArgFct)(struct Cfg_Getopt * const
	, struct Cfg_oStackGetopt * const , int );
typedef char * (*Cfg_sqArgFct)(struct Cfg_Getopt * const
	, struct Cfg_oStackGetopt * const );
typedef void (*Cfg_clArgFct)(struct Cfg_Getopt * const
	, struct Cfg_oStackGetopt * const );
typedef int (*Cfg_ostkEnumFct)(struct Cfg_Getopt * const
	, struct Cfg_oStackGetopt * const , void * const );
typedef int (*Cfg_getIntegerFct)(struct Cfg_Getopt * const);
typedef int (*Cfg_getBooleanFct)(struct Cfg_Getopt * const);
typedef char *(*Cfg_getStringFct)(struct Cfg_Getopt * const);
#endif

struct Cfg_iStackGetopt {		/* stack of indirections */
	struct Cfg_iStackGetopt *C_nxt;
	void *C_getArg;		/* arg may be used by getFct() */
				/* function to fetch a complete token (option or
					argument) */
	Cfg_rdTokFct C_getTokenFct;
				/* function to return the next character */
	Cfg_rdOptFct C_getFct;
				/* function called before closing this stack level */
	Cfg_clOptFct C_closeFct;

	/* How to retreive the argument data in native format */
	Cfg_getIntegerFct C_argIntegerFct;
	Cfg_getBooleanFct C_argBooleanFct;
	Cfg_getStringFct C_argStringFct;

	char *C_buf;		/* current input buffer */
	char C_bufch;		/* current unget()'ed character */
	char *C_poi;		/* current pointer into buf */
	FLAG C_newopt;		/* if poi is start of new option */

		/* save the equally named variables from the main structure
			for the following case: (in _push()/_pop())
			+ configuration: arguments cause getopt() to hang
			+ case: getopt() found an argument
			without saving the current state of these variables (in case
			of an argument, it's 'type' only) and if the user creates
			a new context, this argument is lost, when the state is
			popped */
	int C_type;
	int C_ch;
	char *C_longname;
	char *C_arg;
	char C_bool;
	char C_glbBool;
};

struct Cfg_oStackGetopt {		/* argument buffer stack */
	struct Cfg_oStackGetopt	*C_nxt	/* next ostack in ring */
		, *C_prv;			/* previous ostack in ring */
	int C_cnt;				/* number of entries hosted by this stack item */
	int C_idx;				/* current index for sequential read */
	FLAG C_large;			/* If true, this entry can handle a large
								number of arguments */
	void *C_putArg;			/* arbitary argument(s) for this ostack item */
	Cfg_wrArgFct C_wrArg;	/* write an argument into this output stack item */
	Cfg_rdArgFct C_rdArg;	/* read a specific arg from this ostack item */
	Cfg_sqArgFct C_sqArg;	/* sequential read of arguments */
	Cfg_clArgFct C_clArg;	/* close this ostack item (before it's removed
								from the ostack ring */
};

struct Cfg_Getopt {	/* current command line to scan */
	/* source of scan */
	struct Cfg_iStackGetopt *opt_stk;

	/* scanning properties */
	struct Cfg_LongOptions *optlong;	/* longname options */
	FLAG opt_removeAfterRead;		/* arguments returned by getarg() will
							be permanently removed from the list of
							arguments. Also getargIdx() won't be able to
							retreive them. Also the index numbers of
							the arguments will change. */

	/* filled by getopt() */
	int opttype;			/* type of current pending argument */
	int optch;				/* currently found option (shortname) */
	char *optlongname;		/* if != NULL, longname of found option */
	int optargtype;			/* type of the argument in *optarg, if any */
	char *optarg;			/* argument of the found option; NULL if the
								opt has no arg; "" if arg is empty;
								points into a static buffer or one pushed
								into the input stacks */
	char optbool;			/* boolean sign legal for this option;
								'\0' if none */
	char opt_glbBool;		/* Boolean sign for all the shortname options */

	/* scan flags */
		/* If one or more of the opt_*ch members are NULL and opt_type is
			0 as well (first time cfgGetopt() is called), these variables
			are assigned with the default values as discussed above.
			They are created into the dynamic memory, but they could share
			the same location. */
	char *opt_ch;			/* "normal" option characters */
	char *opt_ioch;			/* in-option option characters */
	char *opt_iach;			/* in-argument option characters */

	char *opt_bool;			/* boolean signs. They are skipped, if they appear
								immediately after the switchar and used
								if they immediately follow an option. They
								default to "+-" and only these two are
								recognized by the internal boolean functions */
	char *opt_arg;			/* argument signs; the rest of the argument right
								of one of these signs is the argument of an
								option. An argument sign that does not follow
								an option is returned as shortname option */
	char *opt_quote;		/* quotes that are used on both sides of the
								quoted string. Defaults to the double quote. */
/*	char opt_squote;		/ * single character quote. DISABLED */
	char *opt_stdin;		/* characters that if found alone on command line
								are to be interpreted as "read stdin" or
								"write stdout" */
	char *opt_stop;			/* characters that if found twice on command
								line alone, any following arguments are
								treated as non-option arguments */
	char opt_sourcein;		/* prefix for non-option arguments that indicates
								a response file; '\0' if none. */

	/* The next functions are called at various circumstances to
		get knowledge how to proceed.

		If there is no function specified, the default behaviour is to
		stop proceeding.

		Return:
			0: ignore/skip the argument 
			1: this argument must be retreived before proceeding
	*/
	Cfg_FctGetopt opt_foundArg;	/* non-option found in getopt() */
	Cfg_FctGetopt opt_foundOpt;	/* option found in getarg() */

	/* how to proceed the scan */
	FLAG opt_optstop;		/* any further arguments are non-option ones */

	/* output properties */
			/* The output stack is organized as a FIFO, if read
				sequentially. Also the ostack items are not removed
				unless they are empty. Items not empty by default,
				can dynamically become empty, or if _deleteAfterRead
				is enabled.

				The ostack items are organized in a ring, meaning
				it's a double linked list which ends are linked
				together.

				oHead points to the item where the argument with
				index #0 resides. If oHead == NULL, no output stack
				is currently available.

				oCur points to the item, in which the sequential read
				arrived. If oCur == NULL, the read starts initially.
			*/
	struct Cfg_oStackGetopt
		 * opt_oHead			/* first ostack item */
		,* opt_oCur;			/* current ostack item */

	/* support for response files */
	size_t opt_hlen;		/* length of help buffer */
	char *opt_hbuf;			/* help buffer */
};

/*
 * Initialize an uninitialized getopt structure with NULL values
 */
void cfgInitGetopt(struct Cfg_Getopt * const optstru);

/*
 *	Release all resources allocated by this getopt structure
 *
 *	This function *must* be called in order to ensure that all
 *	resources are properly freed, e.g. temporary files.
 *
 *	The user _must_ free resources allocated by himself *before* calling
 *	this function.
 *
 *	After the function returnes the Getopt structure is cleared as with
 *	cfgInitGetopt().
 *
 *	It is strongly recommended to make sure cfgExitGetopt() is
 *	execute, because the getopt() process might open temporary files
 *	that are _NOT_ automatically deleted by the C startup (or better
 *	by the C shutdown) code.
 */
void cfgExitGetopt(struct Cfg_Getopt * const optstru);

/*
 *	Sets all options to let getopt() build a list of arguments, but to
 *	ignore the arguments otherwise.
 *	getarg() will read only already processed arguments by getopt().
 *
 *	By default, arguments are cached into memory.
 */
void cfgSetBuildArgList(struct Cfg_Getopt * const optstru);

/*
 *	Return the next option from the initialized structure
 *
 *	Return:
 *		== 0: no further option or non-option argument found
 *		!= 0: shortname option found
 */
int cfgGetopt(struct Cfg_Getopt * const optstru);

/*
 * Add an entry to the argument list
 *
 *	If no such list is maintained (e.g. _addItem == NULL), the call
 *	is silently ignored.
 *	The argument 's' is duplicated into dynamic memory.
 *
 *	's' must not start with *_ch.
 *
 *	addOpt() appends the entry behind, insOpt() before the the last entry.
 */
void cfgAddOpt(struct Cfg_Getopt * const optstru, const char * const s);
void cfgInsOpt(struct Cfg_Getopt * const optstru, const char * const s);

/*
 * Return the next argument
 *
 *	If the flag buildarglst is enabled, the next slot of the lst member
 *	is returned. If it is an response file, it's opened and scanned again.
 *	The returned string can be an option, if its first character is equal
 *	to *_ch; that can be possible when either the user added such entries
 *	or a response file is scanned again.
 *	getopt() have to have returned 0 (zero) already to be sure to return
 *	correct values. (esp. in regards to response files)
 *
 *	If this flag is disabled, this function can be called after cfgGetopt()
 *	returned 0 (zero) to aquire the non-option argument. If this function
 *	returns NULL as well, there is no further argument available.
 *
 *	Return:
 *		NULL: no further argument
 *		else: pointer to the argument, possibly located in the dynamic
 *			memory and no longer available when cfgGetopt() or cfgGetarg()
 *			was called.
 */
char *cfgGetarg(struct Cfg_Getopt * const optstru);

/*
 *	Return the number of cached arguments
 *	only valid if a list of arguments is build.
 */
int cfgArgCount(struct Cfg_Getopt * const optstru);

/*
 *	Return the index of the next argument returned by getarg()
 *	only valid if a list of arguments is build.
 */
int cfgArgIndex(struct Cfg_Getopt * const optstru);

/*
 *	Return a specific argument, if the list of arguments is build
 *
 *	Return:
 *		NULL: not that many arguments cached
 *		else: pointer to argument
 */
char *cfgGetargIdx(struct Cfg_Getopt * const optstru, int idx);

/*
 * Return the type of the next argument
 *
 *	Differs only between CFG_??? (non-option, option, EOF)
 *
 *	Returns one of the CFG_??? macros
 */
int cfgType(struct Cfg_Getopt * const optstru);


/*********************************
 **** Input streams **************
 *********************************/
/*
 * Input streams are "pushed" into an already initialized (cfgInitGetopt())
 * getopt() structure. The last pushed in stream is the first to be read.
 * Streams can be pushed/poped whenever the users wants to, however, poping
 * a streams means to forget all eventually pending input.
 * Streams are automatically poped, when they returned EOF.
 *
 * There are two functions per input stream:
 *	_getFct(), which is called each time one character is needed.
 *		The returned characters are processed in any way, incl. checking
 *		for quotes, argument delimiters etc. So if the input stream is
 *		already broken up or contains only quoted characters, the get
 *		function must quote the characters.
 * _closeFct(), each time, immediately before an input stream is poped,
 *		this function is called in order to free dynamically allocated
 *		resources, such as files and heap memory.
 * The argument _getArg, can be used by the input stream to point to a
 * arbitary buffer describing the input stream, e.g. an file pointer
 * a pointer to a structure.
 */


/*
 *	Push a file to be read, similiar to response files.
 *	This will also activate the "cacheArgs" option.
 */
void cfgPushFile(struct Cfg_Getopt * const optstru
 , const char * const fnam);

/*
 *	Push a dynamically allocted string, which is not preprocessed in
 *	any way. The string is free()'ed when the input stream is poped.
 */
void cfgPushDynString(struct Cfg_Getopt * const optstru
 , const char * const string);

/*
 *	Push a static string, which is not preprocessed in any way.
 */
void cfgPushString(struct Cfg_Getopt * const optstru
 , const char * const string);

/*
 *	Push an already broken up argument array, similiar to the argc/argv
 *	parameters of main(). It is considered that the startup code of
 *	the programs already honored quotes.
 */
void cfgPushArgvQuoted(struct Cfg_Getopt * const optstru, char **argv);

/*
 *	Push an already broken up argument array, similiar to the argc/argv
 *	parameters of main(). It is considered that the startup code of
 *	the programs does not honor quotes. This, however, tends to loose the
 *	correct amount of spaces which were quoted.
 */
void cfgPushArgvNoQuotes(struct Cfg_Getopt * const optstru
 , const char * const * const argv);

/*
 *	Push the command line supplied by DOS.
 *	If this works for the particular compiler is not sure, it may lead to
 *	have only the first argument or none at all.
 */
void cfgPushCmdLine(struct Cfg_Getopt * const optstru);

/*
 *	Push the MKS argument line or, if not present, the normal
 *	command line
 */
void cfgPushMKSargs(struct Cfg_Getopt * const optstru);

/*
 *	Push the contents of an environment variable, if it exists.
 */
void cfgPushEnvVar(struct Cfg_Getopt * const optstru, const char * const var);

/*
 *	Push the local configuration files.
 *	They will always only return longname options.
 */
void cfgPushINIFile(struct Cfg_Getopt * const optstru);


/***************************************
 **** Option interpreting helpers ******
 ***************************************/

/*
 *	All these functions must be called from within an option interpreting
 *	function declared by [extern] Cfg_FctInterprete(fct_name);
 *
 *	Each optGet*(), optScan*(), cfgGet*() and cfgScan*() function has
 *	a corresponding optE*() and cfgE*() function, that terminates the
 *	program with the correct error message.
 *	If one of these functions require a pointer to the argument (aka "num"),
 *	the opt*() counterpart generates the pointer automatically for the cfg*()
 *	function.
 */

/*
 *	Return the base type of the currently attached argument.
 *	Return CFG_TERROR if no argument is available.
 */
#define optArgType() CFG_TBASE(optstru->optargtype)

/*
 *	Return the boolean flag of the current option
 *	Either one of _bool or '\0' for none
 */
#define optHasBool() (optstru->optbool)

/*
 *	Return the current shortname option
 */
#define optName() (optstru->optch)

/*
 *	Return the current longname option, or NULL, if it was shortname
 */
#define optLongName() (optstru->optlongname)

/*
 *	Return the current argument in the proper format.
 *	Note: The functions must not be called, unless the optArgType()
 *	indicates that this current option has the requested type. The
 *	only exception is String(): Every type has a string respresentation
 *	and can therefore be returned as string.
 *	If pointers are returned, they point to an internal buffer that
 *	may be overwritten as soon as another cfg* function is called.
 */
#define optArgInteger()	cfgArgInteger(optstru)
#define optArgBoolean()	cfgArgBoolean(optstru)
#define optArgString()	cfgArgString(optstru)
int cfgArgInteger(struct Cfg_Getopt * const optstru);
int cfgArgBoolean(struct Cfg_Getopt * const optstru);
char *cfgArgString(struct Cfg_Getopt * const optstru);

/*
 *	Check and scan, if so, an unsigned numerical argument of a given range
 *	The range is checked: low <= *num <= high
 *	If radix == 0, C-style is scanned.
 *	Return:
 *		0: success, *num changed
 *		1: number exceeds range
 *		>=10: (position + 10) where the first non-numerical is
 */
#define optGetUnsigned(num, low, high) cfgGetUnsigned(optstru, &(num)	\
		, (low), (high), 0)
int cfgGetUnsigned(struct Cfg_Getopt * const optstru, unsigned * const num
 , unsigned low, unsigned high, int radix);

/*
 *	Check and scan, if so, a signed numerical argument of a given range
 *	The range is checked: low <= *num <= high
 *	If radix == 0, C-style is scanned.
 *	Return:
 *		0: success, *num changed
 *		1: number exceeds range
 *		>=10: (position + 10) where the first non-numerical is
 */
#define optGetSigned(num, low, high) cfgGetSigned(optstru, &(num)	\
		, (low), (high), 0)
int cfgGetSigned(struct Cfg_Getopt * const optstru, int * const num
 , int low, int high, int radix);

/*
 *	Check and scan, if so, a boolean value: on, off, true, false, yes, no
 *	set, clear, +, -, or an unsigned number; toggle, switch
 *	Return:
 *		0: success, *num := 0 (off/false/no/clear/-),
 *			*num := 1 (on, true, yes, set, +), 
 *			*num := 2 (toggle, switch),
 *			*num := (number != 0)
 *		1: no argument at all; *num not changed
 *		2: more than one word on line; *num not changed
 *		3: invalid argument; *num not changed
 */
#define optGetBoolean(num)	cfgGetBoolean(optstru, &(num))
int cfgGetBoolean(struct Cfg_Getopt * const optstru, int * const num);

/*
 *	Interprete boolean option
 *	- If the option has an argument, optGetBoolean() must succeed, then the
 *		action is applied to the given value
 *	- If the option has no argument:
 *	-- If the option has an active boolean sign attched, its value is used.
 *	-- otherwise, the state of the option is toggled.
 *	Return:
 *		0: success
 *		1: no argument at all; *num not changed
 *		2: more than one word on line; *num not changed
 *		3: invalid argument; *num not changed
 */
#define optScanBoolean(num) cfgScanBoolean(optstru, &(num))
int cfgScanBoolean(struct Cfg_Getopt * const optstru, int * const num);

/*
 *	Check and scan, if so, a counter
 *	Counters have the same syntax as boolean options, except they:
 *	+ do not accept toggle and switch, but inc and dec
 *	+ the number can be signed and is added to the current value
 *	Return:
 *		0: success, *num changed
 *		else: failed, *num not changed
 */
#define optGetCounter(num)	cfgGetCounter(optstru, &(num))
int cfgGetCounter(struct Cfg_Getopt * const optstru, int * const num);

/*
 *	Interprete a counter value
 *	As optGetCounter(), but if not argument is given the boolean flags
 *	are evaluated:
 *	* "+" --> set to one (set)
 *	* "-" --> set to zero (clear)
 *	* none --> inc
 *	Return:
 *		0: success, *num changed
 *		1: failed, *num not changed
 */
#define optScanCounter(num)	cfgScanCounter(optstru, &(num))
int cfgScanCounter(struct Cfg_Getopt * const optstru, int * const num);

/*
 *	Check and duplicate, if so, a string
 *	*num _must_ be initialized, as this value is free()'ed.
 *	Return:
 *		0: success
 *		1: failed, no argument, **num not changed
 *		2: no memory, **num not changed
 */
#define optGetString(num)	cfgGetString(optstru, &(num))
int cfgGetString(struct Cfg_Getopt * const optstru, char ** const num);

/*
 *	concatenate strings
 *	*num _must_ be initialized with either NULL or a pointer into the heap
 *
 *	The first character of the string may modify the method of concatenation:
 *	* "+" --> prepend to string already there
 *	* "-" --> overwrite to string already there
 *	* none --> append to string already there (or mode parameter)
 *
 *	The mode parameter may be one of:
 *	CFG_OPT_APPEND, CFG_OPT_PREPEND, CFG_OPT_OVERWRITE, 0 (default)
 *	and optional the flag: CFG_OPT_HONOR_SIGN.
 *
 *	If HONOR_SIGN is given, the '+' and '-' signs are ignored and remain
 *	within the string.
 *	If not HONOR_SIGN and none of the other ones (means '0' is specified),
 *	the default is to append.

 *	delimiter is the character to be placed between two strings, if == '\0'
 *	the strings are not delimited.
 *
 *	On entry, *num must be either NULL or a pointer to a heap block.
 *
 *	If the argument is empty, *num is not changed, but "sucess" is returned.
 *
 *	Return:
 *		0: success
 *		1: failed, no argument, **num not changed
 *		2: no memory, **num not changed
 */
#define optScanString(num,mode,delimiter)	cfgScanString(optstru	\
		, &(num),(mode),(delimiter))
int cfgScanString(struct Cfg_Getopt * const optstru
 , char ** const num, int mode, int delimiter);

/**FLUSH**/

/*********************************
 **** Lowlevel functions *********
 *********************************/
/*
 *	Read the next entry into the Getopt structure _hlen/_hbuf
 *	Terminate the program on failure
 */
void cfg_rsprd(struct Cfg_Getopt * const optstru, FILE * const f);

/*
 *	Write an entry into the response file
 *	Terminate the program on failure
 */
void cfg_rspwr(struct Cfg_Getopt * const optstru, FILE * const f
 , size_t len, const char * const buf);

/*
 *	Push a new state with the supplied values.
 */
void cfg_addContext(struct Cfg_Getopt * const optstru
 , void * const arg, Cfg_rdOptFct get, Cfg_clOptFct close);

/*
 *	Push an argv context with the specified get function
 */
void cfg_pushArgv(struct Cfg_Getopt * const optstru
 , const char * const * const argv
 , Cfg_FctGetopt getfct);

/*
 * Open a new response file and pushes the current state of input sources
 *
 *	Return:
 *		0: could not open response file --> state is not changed
 *		else: on success
 */
int cfg_rspfile(struct Cfg_Getopt * const optstru, const char * const file);

/*
 *	Split an argument from a following option.
 *
 *	The buffer buf[] must remain available until all arguments are
 *	returned by getopt()/getarg(). This is automatically ensured for
 *	arguments returned by the most recent call to getopt() or getarg().
 *
 *	The rest of the buffer behind the first found option character (one of
 *	characters enumerated within optchars) is interpreted as set of options.
 *
 *	The buffer is terminated at the first option character (meaning
 *	the first option character is overwritten with an '\0' character).
 */
void cfgSplitArg(struct Cfg_Getopt * const optstru
 , char * const buf, const char * const optchars);


/*
 *	Split a buffer similiar to cfgSplitArg(), but at the specific position
 *
 *	Note: The character at *p is lost (overwritten by '\0').
 *	To prevent this use a sequence like:
 *		cfgPushDynString(optstru, Estrdup(p));
 */
void cfgSplitBuffer(struct Cfg_Getopt * const optstru, char * const p);

/*
 * Pop the topmost input stream
 *
 *	Return:
 *		0: stack empty
 *		else: on success
 */
int cfg_pop(struct Cfg_Getopt *optstru);

/*
 * Generate and push a new input stream
 *
 *	The members are initialized with dummy values.
 */
void cfg_push(struct Cfg_Getopt *optstru);

/*
 * Insert one output stack item into the ring oHead
 *
 *	The members are initialized with dummy values.
 *	If where == NULL, the new item is appended; otherwise inserted
 *	before the "where" item. If where is no valid ostack item, it
 *	defaults to NULL.
 *
 *	Return:
 *		pointer to new ostack item
 */
#define cfg_ostkNew() cfg_ostkAdd(optstru, 0)
struct Cfg_oStackGetopt *cfg_ostkAdd(struct Cfg_Getopt * const optstru,
	struct Cfg_oStackGetopt * where);

/*
 * Remove the specified output stack item from the ring
 *
 *	Before the item is removed, the clArg function is executed.
 *	If where == NULL, the function does nothing.
 *
 *	Return:
 *		0: ring is empty
 *		else: ring is not empty
 */
int cfg_ostkDel(struct Cfg_Getopt * const optstru,
	struct Cfg_oStackGetopt * where);

/*
 * Calls a function for all output stack items
 *
 *	For each ostack item the functiom
 *	int fct(optstru, ostk, arg) is called
 *
 *	Return:
 *		0: item enumeration runs through all items
 *		else: return value of enumeration function
 */
int cfg_ostkEnum(struct Cfg_Getopt * const optstru,
	Cfg_ostkEnumFct fct, void *arg);


/*********************************
 **** Input stream fnctions ******
 *********************************/

/* get & close function when getArg = FILE*
*/
int cfg_rdFile(struct Cfg_Getopt * const optstru);
void cfg_clFile(struct Cfg_Getopt * const optstru);

/* get function when getArg = argv array, no quotes applied, yet
*/
int cfg_rdArgv(struct Cfg_Getopt * const optstru);

/* get function when getArg = argv array, quotes already applied
*/
int cfg_rdArgvQ(struct Cfg_Getopt * const optstru);

/* get & close function when getArg == dynamical (char*)
*/
int cfg_rdDynString(struct Cfg_Getopt * const optstru);
void cfg_clDynString(struct Cfg_Getopt * const optstru);

/* get function when getArg = static (char*)
*/
int cfg_rdString(struct Cfg_Getopt * const optstru);

/* close function when getArg = dynamically free()'able block
*/
void cfg_clFreeArg(struct Cfg_Getopt * const optstru);


/*********************************
 **** Output stack fnctions ******
 *********************************/

/*
 *	_foundArg() function to add the argument to the current
 *	active output stack item.
 *
 *	Saves the current argument at _buf and returns "0"
 *	to indicate to skip this item in getopt().
 *
 *	Returns "1" (don't ignore) if no output stack is available.
 *	Returns "0" if such item is present, but no write_arg function.
 */
int cfg_addArgToList(struct Cfg_Getopt * const optstru);

/*
 *	Build argument list into a file
 */
void cfg_ostkWrFile(int mode, struct Cfg_Getopt * const optstru
	, struct Cfg_oStackGetopt * const ostk
	, char * const buf
	, size_t len);
char * cfg_ostkRdFile(struct Cfg_Getopt * const optstru
	, struct Cfg_oStackGetopt * const ostk
	, int idx);
char * cfg_ostkSqFile(struct Cfg_Getopt * const optstru
	, struct Cfg_oStackGetopt * const ostk);
void cfg_ostkClFile(struct Cfg_Getopt * const optstru
	, struct Cfg_oStackGetopt * const ostk);
void cfg_ostkInitFile(struct Cfg_oStackGetopt *ostk);

/*
 *	Build argument list into memory
 */
void cfg_ostkWrMem(int mode, struct Cfg_Getopt * const optstru
	, struct Cfg_oStackGetopt * const ostk
	, char * const buf
	, size_t len);
char * cfg_ostkRdMem(struct Cfg_Getopt * const optstru
	, struct Cfg_oStackGetopt * const ostk
	, int idx);
char * cfg_ostkSqMem(struct Cfg_Getopt * const optstru
	, struct Cfg_oStackGetopt * const ostk);
void cfg_ostkClMem(struct Cfg_Getopt * const optstru
	, struct Cfg_oStackGetopt * const ostk);
void cfg_ostkInitMem(struct Cfg_oStackGetopt *ostk);


#endif
