/** SGX

The   sss    gggg x   x   
     s      g      x x    Engine
      sss   g  gg   x
         s  g   g  x x          Copyright 1995-2009.
     ssss    gggg x   x         Steven Goodwin. All Rights Reserved.
    
This version has been released under the GNU Public License v2.0.

Please see the license files for details.

File: sgx/src/domains/filesystem/fileutils.cpp

*/

#include "sgx/core/core.hpp"
#include "domains/filesystem/fileutils.hpp"

tBOOL	sgxFilename::getFilename(sgxString &filename, const sgxString &filepath) {

	tUINT32 pos = filepath.find_last_of('/');

	if (pos == sgxString::npos) {
		filename = filepath;
	} else {
		filename = filepath.substr(pos+1, sgxString::npos);
	}
	return TRUE;
}

tBOOL	sgxFilename::splitPathAndFilename(sgxString &path, sgxString &filename, const sgxString &filepath) {

	tUINT32 pos = filepath.find_last_of('/');

	if (pos == sgxString::npos) {
		path = "";
		filename = filepath;
	} else {
		path = filepath.substr(0, pos);
		filename = filepath.substr(pos+1, sgxString::npos);
	}
	return TRUE;
}

tBOOL	sgxFilename::splitNameAndExtension(sgxString &filename, sgxString &ext, const sgxString &filepath) {

	tUINT32 pos = filepath.find_last_of('.');

	if (pos == sgxString::npos) {
		filename = filepath;
		ext = "";
		return FALSE;
	}

	filename = filepath.substr(0, pos);
	ext = filepath.substr(pos+1, sgxString::npos);
	return TRUE;
}

tBOOL	sgxFilename::getExtension(sgxString &ext, const sgxString &filepath) {

	tUINT32 pos = filepath.find_last_of('.');

	if (pos == sgxString::npos) {
		ext = "";
		return FALSE;
	}

	ext = filepath.substr(pos+1, sgxString::npos);
	return TRUE;
}

tBOOL	sgxFilename::replaceExtension(sgxString &filepath, const sgxString &ext) {

	tUINT32 pos = filepath.find_last_of('.');

	if (pos == sgxString::npos) {
		filepath += ext;
		return FALSE;
	}

	filepath = filepath.substr(0, pos);
	if (ext != "") {
		filepath += ".";
		filepath += ext;
	}

	return TRUE;
}

/**
The 'path root' is the part of the filename at the end, which 
differs between the two paths.
e.g.
pathroot=/project/wii/game1
fullpath=/project/wii/texture/game2

filepath/tail = texture/game2
*/
tBOOL sgxFilename::extractPathRoot(sgxString &filepath, const sgxString &pathroot, const sgxString &fullpath) {
	const char *p1 = pathroot.c_str();
	const char *p2 = fullpath.c_str();
	while(*p1 == *p2) {
		++p1;
		++p2;
	}
	filepath = p2;
	return TRUE;
}

tBOOL sgxFilename::getBaseName(sgxString &basename, const sgxString &path) {
tINT32 pos = path.find_last_of('/');
		
	if (pos == -1) {
		basename = path;
		return FALSE;
	}
	basename = path.substr(pos+1, sgxString::npos);
	return TRUE;
}

tBOOL sgxFilename::getParent(sgxString &parentPath, const sgxString &path) {
tINT32 pos = path.find_last_of('/');
		
	if (pos == -1) {
		parentPath = "";
		return FALSE;
	}
	parentPath = path.substr(0, pos);
	return TRUE;
}

