/***********************************************
 * This is a parser specifically for our program
 * that is "safer" than strtok.
 * we avoid the use of static variables
 * used by strtok to make it thread safe
 * *********************************************/

#include "parser.h"

int parse(char strToParse[], char delimeter, int tok_ns[], int nbuff, int ntok) 
{
	/*
	 * PRECONDITIONS: the number of index should
	 * 		be big enough to hold all the tokens
	 *		and the delimeter can only be of one 
	 *		character. Each of the different 
	 *		threads calling parser must have
	 *		their own character strings.
	 * POSTCONDITIONS: the int returned is the number of 
	 * 		indexes successfully parsed.
	 * 		Thus we can access up to n - 1
	 * 		tokens.
	 * FEATURES: 	the single char delimeter is replaced
	 * 	     	with the end of string character. 
	 */
	int str_index = 0;
	int token_index = 0;
	
	/* check for the index of first token */
	if (strToParse[0] != delimeter)
		tok_ns[token_index++] = str_index;

	/* grab the rest of the tokens */	
	for (str_index = 0; str_index < nbuff; str_index++) {		
		if (strToParse[str_index] == '\377') {
			// parity or framing error
			return -1;
		}
		if (strToParse[str_index] == delimeter) {
			strToParse[str_index] = '\0';
			if (token_index < ntok) {
				tok_ns[token_index++] = str_index + 1; 	
			}
			
		}
	}

	return token_index;

}

int parse_vision(char strToParse[], char delimeter, int tok_ns[], int nbuff, int ntok)
{
	/*
	 * PRECONDITIONS: the number of index should
	 * 		be big enough to hold all the tokens
	 *		and the delimeter can only be of one
	 *		character. Each of the different
	 *		threads calling parser must have
	 *		their own character strings.
	 * POSTCONDITIONS: the int returned is the number of
	 * 		indexes successfully parsed.
	 * 		Thus we can access up to n - 1
	 * 		tokens.
	 * FEATURES: 	the single char delimeter is replaced
	 * 	     	with the end of string character.
	 */
	int str_index = 1;
	int token_index = 0;
	
	/* check for the index of first token */
	if (strToParse[0] != delimeter)
		tok_ns[token_index++] = str_index;
        else	{
         	while(strToParse[++str_index] == delimeter) strToParse[str_index] = '\0';
         	tok_ns[token_index++] = str_index;
         	}
         	
	/* grab the rest of the tokens */	
	for (str_index+1; str_index < nbuff; str_index++) {		
		if (strToParse[str_index] == '\377') {
			// parity or framing error
			return -1;
		}
		if (strToParse[str_index] == delimeter) {
			strToParse[str_index] = '\0';
			while(strToParse[++str_index] == delimeter) strToParse[str_index] = '\0';
			if (token_index < ntok) {
				tok_ns[token_index++] = str_index; 	
			}
			
		}
	}

	return token_index;

}


     

