#include<string.h>

#ifndef NULL
#define NULL 0
#endif

#ifndef HAVE_STRSEP
/*
STRSEP(3)           Linux Programmer's Manual           STRSEP(3)

NAME
       strsep - extract token from string

SYNOPSIS
       #include <string.h>

       char *strsep(char **stringp, const char *delim);

DESCRIPTION
       The  strsep()  function  returns  the  next token from the
       string stringp which is delimited by delim.  The token  is
       terminated with a `\0' character and stringp is updated to
       point past the token.

RETURN VALUE
       The strsep() function returns a pointer to the  token,  or
       NULL if delim is not found in stringp.

NOTES
       The  strsep() function was introduced as a replacement for
       strtok(), since the latter  cannot  handle  empty  fields.
       (However,  strtok()  conforms  to ANSI-C and hence is more
       portable.)

CONFORMING TO
       BSD 4.4

SEE ALSO
       index(3),  memchr(3),  rindex(3),  strchr(3),  strpbrk(3),
       strspn(3), strstr(3), strtok(3)

GNU                       April 12, 1993                        1
*/
char * strsep( char ** stringp, const char * delim )
{
  char *begin, *end;

  begin = *stringp;
  if (begin == NULL)
    return NULL;

  /* A frequent case is when the delimiter string contains only one
     character.  Here we don't need to call the expensive `strpbrk'
     function and instead work using `strchr'.  */
  if (delim[0] == '\0' || delim[1] == '\0')
    {
      char ch = delim[0];

      if (ch == '\0')
        end = NULL;
      else
        {
          if (*begin == ch)
            end = begin;
          else
            end = strchr (begin + 1, ch);
        }
    }
  else
    /* Find the end of the token.  */
    end = strpbrk (begin, delim);

  if (end)
    {
      /* Terminate the token and set *STRINGP past NUL character.  */
      *end++ = '\0';
      *stringp = end;
    }
  else
    /* No more delimiters; this is the last token.  */
    *stringp = NULL;

  return begin;
}
#endif
