/* Created 11/08/87 by -=+SDB+=- from cliparse.c provided by Manx */
/* Copyright (C) 1987 by Scott Ballantyne */
/* May be freely used by arp supporters/users */

/* This routine is called from _main() and parses the arguments passed from
 * the CLI to the program.  It uses the ARP tracking functions to allocate
 * memory for the argv array, and sets up _argc and _argv (using GADS)
 * which will eventually be passed as parameters to main().
 *
 * It uses the Global variables CLI_Template and CLI_Help to set the command
 * templates and extra help string for GADS() - if you don't set these up
 * yourself, you get the defaults.
 */

extern int _argc;
extern char **_argv;
extern char *CLI_Template;
extern char *CLI_Help;
extern char *_detach_name;			/* for DETACHED programs */

_cli_parse(struct Process *pp,long alen,char *aptr)
{
	struct CommandLineInterface	*cli;
	char				*c,*cp;
	int				 argcount,length;

	if(pp -> pr_CLI)
	{
		cli = (struct CommandLineInterface *)BADDR(pp -> pr_CLI);
		cp = (char *)BADDR(cli -> cli_CommandName);
	}
	else
		cp = _detach_name;

	length = cp[0]; 		/* Length of command name */

	/* argcount *must* start at 3, do not change this.
	 * we need one for argv[0] = progname, and GADS() always
	 * requires one arg entry (for error messages, etc.)
	 * Then it is quasi standard for 'C' to have a final NULL as
	 * the argv array...
	 */

	for(argcount = 3,c = CLI_Template ; *c ; c++) /* Size we need for argv */
	{
		if(*c == ',')
			argcount++;
	}

	if(!(c = ArpAlloc(length)))  /* Get mem for name */
		ArpExit(20L,ERROR_NO_FREE_STORE);

	strncpy(c,&cp[1],cp[0]);

	if(!(_argv = ArpAlloc((argcount * sizeof(*_argv)))))
		ArpExit(20L,ERROR_NO_FREE_STORE);

	_argv[0] = c;

	_argc = (int)GADS(aptr,alen,CLI_Help,(_argv + 1),CLI_Template);

	if(_argc < 0)
	{
		Printf("Bad Args for %s: %s\n",_argv[0],_argv[1]);

		ArpExit(20,ERROR_LINE_TOO_LONG);
	}

	_argc++;
}
