#include <ctype.h>
#include <stdlib.h>
#include <string.h>

#include <exec/types.h>

/* Function Prototypes */
LONG next_word( UBYTE *buffer, LONG pos, LONG max );
LONG prev_word( UBYTE *buffer, LONG pos );
char *IncrementNum( char *target, char *string );
void ToggleCase( UBYTE *character );

/* Maximum length of number substrings */
#define MAXLEN 20

LONG next_word( UBYTE *buffer, LONG pos, LONG max )
{
	while ( pos < max && !isspace( buffer[ pos ] ) ) pos++;
	while ( pos < max && isspace( buffer[ pos ] ) ) pos++;

	return pos;
}

LONG prev_word( UBYTE *buffer, LONG pos )
{
	while ( pos > 0 && isspace( buffer[ pos - 1 ] ) ) pos--;
	while ( pos > 0 && !isspace( buffer[ pos - 1 ] ) ) pos--;
	return pos;
}

char *IncrementNum( char *target, char *string )
{
	char *num_start, *num_end = NULL;
	char numstr[ MAXLEN + 1 ];
	int i, j = 0, pos, number;
	BOOL FoundNumber = FALSE;

	/* Clear the target string */
	target[0] = 0;

	/* Position the search after any :'s or /'s to ignore paths */
	for ( pos = strlen( string ); pos > 0; pos-- )
	{
		if ( string[pos] == ':' || string[pos] == '/' )
		{
			pos++;
			break;
		}
	}

	/* Locate the last number in the string */
	for ( i = strlen( string ); i >= pos; i-- )
	{
		/* Locate a digit character */
		if ( isdigit( string[i] ) != 0 )
		{
			/* Store a pointer to this location in string[] */
			num_end = &string[i];

			/* Copy out the embedded number - including leading zeros */
			while ( isdigit( string[i] ) != 0 )
			{
				numstr[ j++ ] = string[i--]; // Copy the number

				numstr[j] = 0; // Terminate the string

				if ( j == MAXLEN ) break; // Only for as long as our temporary string
			}
			strrev( numstr ); // String will be in reverse
			number = atoi( numstr ); // Convert to a decimal number
			FoundNumber = TRUE;

			break; // Get outta this loop
		}
	}

	/* If we didn't find a number, abort */
	if ( FoundNumber == FALSE ) return NULL;

	/* Find the start position of our number substring */
	num_start = num_end - strlen( numstr ) + 1;

	/* Increment the number */
	number++;

	/* Store length of the original number string - including leading zeros */
	j = strlen( numstr );

	/* Calculate the length of the bit before the number */
	i = num_start - string;

	/* Convert the new number back to a string */
	stci_d( numstr, number );

	/* Copy the first part of string[] into our new destination */
	strncat( target, string, i );

	/* Add leading zeros - if required */
	if ( j > strlen( numstr ) )
	{
		for ( i = 0; i < j - strlen( numstr ); i++ )
		{
			strcat( target, "0" );
		}
	}

	/* Add the new number */
	strcat( target, numstr );

	/* Add the remaining part of string[] */
	strcat( target, num_start + j );

	return target;
}

void ToggleCase( UBYTE *character )
{
	/* Only touch alphabetical characters */
	if ( isalpha( *character ) != 0 )
	{
		if ( islower( *character ) != 0 ) *character = toupper( *character );
		else *character = tolower( *character );
	}
}
