////////////////////////////////////////////////////////////////////////////
//
//  Crytek Engine Source File.
//  Copyright (C), Crytek Studios, 2002.
// -------------------------------------------------------------------------
//  File name:   fileutil.cpp
//  Version:     v1.00
//  Created:     5/11/2002 by Timur.
//  Compilers:   Visual Studio.NET
//  Description: 
// -------------------------------------------------------------------------
//  History:
//
////////////////////////////////////////////////////////////////////////////

#include "StdAfx.h"
#include "FileUtil.h"

#include <io.h>

//////////////////////////////////////////////////////////////////////////
// the paths must have trailing slash
static bool ScanDirectoryRecursive( const string &root,const string &path,const string &file,std::vector<string> &files, bool recursive )
{
	__finddata64_t c_file;
	intptr_t hFile;

	bool anyFound = false;

	string fullPath = PathHelpers::Join(PathHelpers::Join(root, path), file);
	if ( (hFile = _findfirst64( fullPath.c_str(), &c_file )) != -1L )
	{
		// Find the rest of the files.
		do {
			if (!(c_file.attrib & _A_SUBDIR))
			{
				anyFound = true;
				files.push_back( PathHelpers::Join(path, c_file.name) );
			}
		}	while (_findnext64( hFile, &c_file ) == 0);
		_findclose( hFile );
	}

	if (recursive)
	{
		fullPath = PathHelpers::Join(PathHelpers::Join(root, path), "*.*");
		if( (hFile = _findfirst64( fullPath.c_str(), &c_file )) != -1L )
		{
			// Find directories.
			do {
				if (c_file.attrib & _A_SUBDIR)
				{
					// If recursive.
					if (c_file.name[0] != '.')
					{
						if (ScanDirectoryRecursive( root,PathHelpers::Join(path, c_file.name),file,files,recursive ))
							anyFound = true;
					}
				}
			}	while (_findnext64( hFile, &c_file ) == 0);
			_findclose( hFile );
		}
	}

	return anyFound;
}

//////////////////////////////////////////////////////////////////////////
namespace FileUtil
{
	bool ScanDirectory( const string &path,const string &file,std::vector<string> &files, bool recursive )
	{
		return ScanDirectoryRecursive(path,"",file,files,recursive );
	}
}
