/*
 * nqs_generic/all-systems/parseserv.c
 * Parse command line arguments.
 */

#include <nqs_generic/license.h>
  /* NQS license information */
#include <nqs_generic/debug.h>
  /* debugging support */
#include <nqs_generic/proto.h>
  /* ANSI C prototype support */

#include <nqs_generic/nqs_generic.h>
  /* old nqs.h */

#include <string.h>

static char *scanwhite ( char *ch );

/*** parseserv
 *
 *	int parseserv ():
 *	Parse server command line into argv[].
 *
 *	Returns:
 *		0: if successful.
 *	       -1: if there are too many arguments, or the server
 *		   specification is too long.
 */
int parseserv (char *servercmd, char *argv[MAX_SERVERARGS+1])
{
  static char serverspec [MAX_SERVERNAME+1];
    /* Server command and arguments */
  register int i;
    /* Index */
  register char *cp;
    /* Character pointer */

  ENTER_FUNCTION("nqs_generic/all-systems/parseserv");
    /* debugging support */
  TEST_ARG(servercmd != NULL, 1);
  TEST_ARG(argv      != NULL, 2);
    /* ensure we are not working with garbage */
  
  if (strlen (servercmd) > MAX_SERVERNAME)
    return (-1);
  
  strcpy (serverspec, servercmd);
    /* Copy the server command into */
  i = 0;
    /* the static buffer area */
  cp = serverspec;
  do
  {
    cp = scanwhite (cp);
      /* Scan white space */
    if (*cp)
    {
      /*
       *  We have an argument.
       */
      argv [i] = cp;
        /* Record start of argument */
      do
      {	
	/* Scan argument */
	cp++;
      } while (*cp > ' ');
      
      if (*cp)
      {
	/*
	 *  Null terminate argument.
	 */
	*cp = '\0';
	cp++;
      }
    }
    i++;
  } while (*cp && i < MAX_SERVERARGS);
  
  argv [i] = NULL;
    /* Null terminate argv[] list */
  cp = scanwhite (cp);
  if (*cp != '\0')
  {
    /*
     *  Too many server arguments in server command line.
     */
    EXIT_FUNCTION;
    return (-1);
  }
  else
  {
    EXIT_FUNCTION;
    return (0);			/* Parse was successful */
  }
  NEVER;
    /* This line should never be reached */
  return 0;
    /* Keep compiler happy - compile without warnings */
}

/*** scanwhite
 *
 *
 *	char *scanwhite():
 *
 *	Scan white space returning pointer to first non-white character
 *	or null character.  This function only works for 7-bit ASCII
 *	characters.
 */
static char *scanwhite (char *ch)
{
  ENTER_FUNCTION("nqs_generic/all-systems/scanwhite");
  TEST_ARG(ch != NULL, 1);
    /* ensure we are not working with garbage */
  while (*ch && *ch <= ' ')
    ch++;
  
  EXIT_FUNCTION;
  return (ch);
}
