#include <stdio.h>
#include <ctype.h>
#include <strings.h>
#include "stringops.h"
#define tolow(A) (isupper(A)?(tolower(A)):(A))

int strcasecmp (char *a, char *b)
{
	#ifdef FUNCTIONS
	puts ("strcasecmp");
	#endif

	for (; (*a != '\0') && (*b != '\0') && (tolow (*a) == tolow (*b));
		a++, b++);
	return (tolow (*a) - tolow (*b));
}

int strncasecmp (char *a, char *b, int n)
{
	#ifdef FUNCTIONS
	puts ("strncasecmp");
	#endif

	for (; (*a != '\0') && (*b != '\0') &&
		(tolow (*a) == tolow (*b)) && (n  > 0); a++, b++, n--);
	if (n == 0)
		return 0;
	return (tolow (*a) - tolow (*b));
}

int wordlen (char *string)
{
	int counter = 0;

	#ifdef FUNCTIONS
	puts ("**wordlen");
	#endif

	while (isalnum(*string)) string++, counter++;
	return counter;
}

void lowercase (char *string)
{
	#ifdef FUNCTIONS
	puts ("**lowercase");
	#endif

	while (*string != '\0')
	{
		if ((*string >= 'A') && (*string <= 'Z'))
			*string += 32;
		string++;
	}
}

char *findstr(char *tststr, char *string)
{
	int length;

	#ifdef FUNCTIONS
	puts ("**findstr");
	#endif

	length = strlen(string);
	while ((*tststr != '\0') &&
		((strncmp(tststr, string, length))))
		tststr++;
	if (*tststr != '\0') return tststr;
	return NULL;
}

/* find - finds a string, making sure it is not a substring. */
char *find(char *string, char *searchstring)
{
	#ifdef FUNCTIONS
	puts ("**find");
	#endif

	while (!isalnum(*string) && (*string != '\0')) string++;
	while (isalnum(*string))
	{
		if (!strncasecmp(string, searchstring, strlen(searchstring)) &&
			!isalnum(*(string + strlen(searchstring))))
			return string;
		while (isalnum(*string)) string++;
		while ((*string != '\0') && !isalnum(*string)) string++;
	}
	return NULL;
}

char *quotestrip(char *i)
{
	char data[200], *returndata, *start, *end;
	int dataloc;

	#ifdef FUNCTIONS
	puts ("**quotestrip");
	#endif

	start = i;
	end = i;

	while ((*start != '\"') && (*start != '\0')) start++;
	if (*start == '\0') return NULL;
	while (*end != '\0') end++;
	while (*end != '\"') end--;
	if (end == start) return NULL;
	for (dataloc = 1; dataloc + start < end; dataloc++)
		data[dataloc - 1] = start[dataloc];
	data[dataloc - 1] = '\0';

	returndata = (char *)calloc(strlen(data) + 1, sizeof(char));
	strcpy (returndata, data);
	return returndata;
}

char *tokenize(char *dest, char *source)
{
	#ifdef FUNCTIONS
	puts ("**tokenize");
	#endif

	if (source == NULL)
	{
		*dest = '\0';
		return NULL;
	}
	while ((*source != '\0') && (!isspace(*source)))
		*(dest++) = *(source++);
	*dest = '\0';
	return ((*source == '\0')?NULL:source + 1);
}

char *clip (char *start, char *end)
{
	char *retstr;
	int length;

	#ifdef FUNCTIONS
	puts ("**clip");
	#endif

	length = end - start + 1;

	retstr = (char *)calloc(sizeof(char), length + 1);
	strncpy(retstr, start, length);
	retstr[length]='\0';

	return retstr;
}