#ifdef _WIN32
#include <windows.h>
#include <direct.h>
#endif

#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include <sys/stat.h>

/*
===============
DoDirectoryWork

Performs an action (function) on files (filespec) in a directory (directory)  
===============
*/
int DoDirectoryWork (char *directory, char *filespec, char *skip, int (*function)(char *))
{
	HANDLE           dirHandle;
	WIN32_FIND_DATA  findData;
	int              found = 1;
	char             temp[128];
	char			filename[1024];
	
	sprintf(temp, "%s\\%s", directory, filespec);

	dirHandle = FindFirstFile(temp, &findData);

	if (dirHandle == INVALID_HANDLE_VALUE)
		return 0;

	while (found)
	{
		// if this is a direcory then recuruse
		if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
		{
			if (findData.cFileName[0] != '.')
			{
			    sprintf(temp, "%s\\%s", directory, findData.cFileName);
				DoDirectoryWork(temp, filespec, skip, function);
			}
		}
		else
		{
			strlwr (findData.cFileName);
			strlwr (skip);

			if (strstr (findData.cFileName, skip))
			{
				found = FindNextFile(dirHandle, &findData);
				continue;
			}

			sprintf (filename, "%s/%s", directory, findData.cFileName);

			if (!function (filename))
				return 0;
		}

		found = FindNextFile(dirHandle, &findData);
	}

	FindClose(dirHandle);

	return 1;
}

/*
===============
CheckDirectoryName

===============
*/
int CheckDirectoryName (char *name)
{
	char	dir[1024];
	char	*token;

	if ((_getcwd (dir, 1024)) == NULL )
	{
		printf ("Error getting current working directory\n");
		exit (0);
	}

	token = strtok (dir, "\\");

	while (token != NULL)
	{
		if (!strcmp (token, name))
		{
			// make sure that "name" is the current directory and that we are not passed it
			token = strtok (NULL, "\\");
			if (token)
			{
				printf ("Error getting current working directory\n");
				exit (0);
			}

			return 1;
		}

		token = strtok (NULL, "\\");
	}
	return 0;
}
