/*
 * Copyright (c) 2004, 2005 Sendmail, Inc. and its suppliers.
 *	All rights reserved.
 *
 * By using this file, you agree to the terms and conditions set
 * forth in the LICENSE file which can be found at the top level of
 * the sendmail distribution.
 */

#include "sm/generic.h"
SM_RCSID("@(#)$Id: str2argv.c,v 1.6 2005/06/09 00:43:40 ca Exp $")

#include "sm/assert.h"
#include "sm/magic.h"
#include "sm/memops.h"
#include "sm/ctype.h"
#include "sm/rpool.h"
#include "sm/strrcb.h"
#include "sm/str-int.h"
#include "sm/str2rcb.h"

/*
**  SM_STR2ARGV -- split string into arguments
**	(delimiter: ISSPACE())
**
**	Parameters:
**		str -- string to split
**		offset -- offset at which to start
**		maxargs -- size of argv
**		argv -- fill in with offsets
**
**	Returns:
**		usual return code
**
**	Side Effects:
**		replaces space characters in str with '\0'
*/

sm_ret_T
sm_str2argv(sm_str_P str, uint offset, uint maxargs, uint *argv)
{
	uint i;
	uchar c;
	uint arg;

	SM_REQUIRE(str != NULL);
	SM_REQUIRE(argv != NULL);
	SM_REQUIRE(maxargs > 0);

	sm_memzero(argv, maxargs * sizeof(argv[0]));
	for (i = offset, arg = 0;
	     i < sm_str_getlen(str) && (c = sm_str_rd_elem(str, i)) != '\0';
	     i++)
	{
		while (i < sm_str_getlen(str)
		       && (c = sm_str_rd_elem(str, i)) != '\0'
		       && ISSPACE(c))
			++i;
		if (i >= sm_str_getlen(str))
			break;

		argv[arg++] = i;
		while (i < sm_str_getlen(str)
		       && (c = sm_str_rd_elem(str, i)) != '\0'
		       && ISASCII(c) && !ISSPACE(c))
			++i;
		if (i >= sm_str_getlen(str))
			break;
		if ((c = sm_str_rd_elem(str, i)) != '\0' && ISASCII(c)
		    && ISSPACE(c))
			sm_str_wr_elem(str, i, '\0');

		if (arg >= maxargs)
			return sm_err_perm(E2BIG);
	}
	return arg;
}



syntax highlighted by Code2HTML, v. 0.9.1