/* Copyright (C) 2000 Damir Zucic */

/*=============================================================================

				extract_token.c

Purpose:
	Extract token (substring) from string. Up to max_length - 1
	characters are copied.

Input:
	(1) Pointer to the buffer where token will be stored.
	(2) The maximal length of the token (counting '\0').
	(2) Pointer to the input string.
	(3) Pointer to the list (string) of separators.

Output:
	(1) Token extracted and copied.
	(2) Return value.

Return value:
	(1) Pointer to the next token, on success.
	(2) NULL on failure.

Notes:
	(1) Input overflow is not allowed in this function.

	(2) The output token is always terminated properly.

========includes:============================================================*/

#include <stdio.h>

/*======extract token:=======================================================*/

char *ExtractToken_ (char *tokenP, int max_length,
		     char *stringP, char *separatorsP)
{
int		current_char, current_separator;
int		separator_foundF, token_foundF;
char		*P;
int		token_length = 0;

/* Initialize the output string: */
*tokenP = '\0';

/* Check the input string pointer: */
if (stringP == NULL) return NULL;

/* Skip leading separators: */
token_foundF = 0;
while ((current_char = *stringP++) != '\0')
	{
	/** Search the set of separators: **/
	P = separatorsP;
	separator_foundF = 0;
	while ((current_separator = *P++) != '\0')
		{
		if (current_char == current_separator)
			{
			separator_foundF = 1;
			break;
			}
		}

	/** If the current character  does not belong to **/
	/** the set of separators, the token is reached: **/
	if (!separator_foundF)
		{
		token_foundF = 1;
		break;
		}
	}

/* Pointer to the last character; this is either */
/* zero or  the first  character  of the  token: */
stringP--;

/* If token was not reached at all, return NULL: */
if (*stringP == '\0') return NULL;

/* Copy the token: */
while ((current_char = *stringP++) != '\0')
	{
	/** Search the set of separators: **/
	P = separatorsP;
	separator_foundF = 0;
	while ((current_separator = *P++) != '\0')
		{
		if (current_char == current_separator)
			{
			separator_foundF = 1;
			break;
			}
		}

	/** If the current character belongs to the set **/
	/** of separators, the end of token is reached: **/
	if (separator_foundF) break;

	/** If end of token is not reached, copy the current character: **/
	*tokenP++ = current_char;

	/** Update and check the token length: **/
	token_length++;
	if (token_length >= max_length - 1) break;
	}

/* Terminate the token: */
*tokenP = '\0';

/* Return the pointer to the remainder of the string: */
return --stringP;
}

/*===========================================================================*/


