#include "parse.h" 
#include "alloc.h"

 /*
 |  Decides whether a character is whitespace or not
*/
int parseCheckIsWhite( c )
char	c;
{
	if( c==' ' || c=='\t' )
		return 1;
	return 0;
}

 
 /*
 |  Returns a string as an array of pointers to 
 |  space separated parts
*/
void parseSeparate( str, ptrs )
char	*str,
	*ptrs[];
{
	char	*pos = str,
		**this = ptrs;

	/* Skip leading whitespace */
	while( *pos && parseCheckIsWhite( *pos ) )
		pos++;

	/* Move through rest of the string */
	while( *pos )
	{
		/* Start of current word */
		*this++ = pos;
		/* Skip over colourspace (current word) */
		while( *pos && !parseCheckIsWhite( *pos ) )
			pos++;
		/* Introduce a fake terminator */
		if( *pos )
			*pos++ = 0;
		else
			break;
		/* Skip over whitespace gap */
		while( *pos && parseCheckIsWhite( *pos ) )
			pos++;
	}
	*this = 0;	/* End marker */
}


/* First name is the list */
static variable *firstvar = 0;


 /*
 |  Try to locate a variable name is the list
*/
variable *parseFindName( name )
char	*name;
{
	variable *this = firstvar;

	/* Search the list */
	while( this && strcmp( this->name, name ) )
		this = this->next;

	/* Either list is empty, or name is not in it */
	if( this == 0 )
		return( 0 );

	return( this );
}


 /*
 |  Add a variable to the list, overriding old value
 |  Z's Hot Cross Bun operator
*/
variable *parseAddName( name, exp )
char	*name;
char	*exp;
{
	variable *this = parseFindName( name ),
	         *new;

	/* Variable already exists */
	if( this )
	{
		if( strcmp( this->exp, exp ) )
		{
			/* Value is changing */
			wfree( this->exp );
			this->exp = wmalloc( strlen(exp)+1 );
			strcpy( this->exp, exp );
			return( this );
		}
		else
			/* Value isn't changing */
			return( this );
	}

	/* Create a new variable */
	new = (variable*)wmalloc( sizeof(variable) );
	new->next = 0;
	if( (this=firstvar) == 0 )
	{
		firstvar = this = new;
	}
	else
	{
		while( this->next )
			this = this->next;
		this->next = new;
	}

	new->name = wmalloc( strlen(name)+1 );
	strcpy( new->name, name );
	new->exp = wmalloc( strlen(exp)+1 );
	strcpy( new->exp, exp );

	return( new );
}


