/* xPresence.cp */

#include "xPresence.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

/*
	Give this inputStr and it looks for an 'x'. If it does not find 'x' it
	returns false.
	
	If it does find an x, it finds the highest power of x and returns that
	in the n variable
*/

bool xPresence(const char* inputStr, int& n)
{
	int			i, j, length, thePower;
	char		*dataString, ch;
	bool		xExists;
	
	length = strlen(inputStr);
	if(length==0)
		return false;
	
	// search for any x
	xExists = false;
	for(i=0;i<length;i++)
		if(inputStr[i]=='x')
		{
			xExists = true;
			break;
		}
	
	if(!xExists)
		return false;
		
	// now we have x's
	n = 0;
	
	dataString = (char *)malloc((length+1)*sizeof(char));
	
	i = 0;
	getTheNext:
	// search for next x
	if(i>=length)
	{
		goto myExitTrue;
	}
	ch = inputStr[i];
	while(i<length && ch!='x')
		ch = inputStr[++i]; // i points to current value of ch
		
	// if ch='x' on first try, i=0 and points to 'x'
	// on later tries i still points to 'x' or else i=length and ch=0
	
	if(i>=length)
	{
		goto myExitTrue;
	}
	
	// now i points to 'x'
	// get rid of white space, if there is any
	ch = inputStr[++i];
	while(i<length && ch<=32)
		ch = inputStr[++i]; // i points to current value of ch
		
	if(i>=length)
	{
		thePower = 1;
		if(thePower>n)
			n = thePower;
		goto myExitTrue;
	}
	
	// 
	
	// is ch a '^' ?
	
	if(ch!='^')
	{
		thePower = 1;
		if(thePower>n)
			n = thePower;
		i++;
		goto getTheNext;
	}
	
	// now ch='^' and i points to it
	
	if(i>=(length-1))
	{
		goto myExitFalse;
	}
	
	// get rid of white space, if there is any
	ch = inputStr[++i];
	while(i<length && ch<=32)
		ch = inputStr[++i]; // i points to current value of ch
		
	if(i>=length)
	{
		goto myExitFalse;
	}
	
	// get the power
	j = 0;
	if(ch=='+' || ch=='-')
	{
		dataString[j++] = ch;
		ch = inputStr[++i];
	}
	
	while(i<length && ch!='+' && ch!='-')
	{
		dataString[j++] = ch;
		ch = inputStr[++i]; // i points to current value of ch
	}
	dataString[j] = 0;
	
	if(sscanf(dataString, "%d", &thePower)!=1)
		goto myExitFalse;
	
	if(thePower>n)
		n = thePower;
	
	goto getTheNext;
	
	myExitTrue:
	free(dataString);
	return true;
	
	myExitFalse:
	free(dataString);
	return false;
	
}/* xPresence */
