/*
** TokenString.m,v 1.2 1992/05/21 22:47:36 nwc Exp
**
** Copyright (c) 1991 Ronin Consulting, Inc.
*/

#import "TokenString.h"
#import <string.h>

@implementation TokenString

- init: (const char *) string
{
   [super init: string];
   separator = ' ';
   lastEnd = (char)0;
   nullTokens = NO;
   return self;
}

- setStringValue: (const char *) string
{
   [super setStringValue: string];
   start = (char *)[self elementAt: 0];
   return self;
}

- setSeparator: (char) aChar
{
   separator = aChar;
   return self;
}

- (char) separator
{
   return separator;
}

- setNullTokens: (BOOL) toggle
{
   nullTokens = toggle;
   return self;
}

- (BOOL) nullTokens
{
   return nullTokens;
}


- (const char *) popString
{
   char *ptr = start;

   while(*start && *start != separator)	     /* advance to null or separator*/
       start++;

   if(start == ptr)			     /* start did not advance - at the end of a 0 length token */
   {
      if(*start)			     /* zero length due to a separator */
      {
	 if(!nullTokens)		     /* if nullTokens don't fly here skip consecutive separators */
	 {
	    while(*start == separator)
		start++;
	 
	    return([self popString]);		     /* passed the separators try again */
	 }
      }
      else				     /* zero length due to a null */
      {
	 if(!(nullTokens && lastEnd))	     /* we don't take null tokens or last time though we hit a null */
	     return (const char *)0;

	 lastEnd = *start;
	 return "";			     /* return a null token */
      }
   }
   
   
   /* 
    * Token had length.
    */

   lastEnd = *start;

   if(*start)				     /* separator */
   {
      *start = (char)0;

      if(!nullTokens)			     /* if no null tokens get rid of the multiple separators */
	  while(start[1] == separator)
	      start++;

      start++;				     /* step past separator */
   }
   
   return (const char *)ptr;
}      

@end
