#include "StdAfx.h"
#include "CBAHelpers.h"
#include "../PathHelpers.h"

string CBAHelpers::FindCBAFileForFile(const string& filePath, IPakSystem* pakSystem)
{
	const string relativeCBAPath = "Animations/Animations.cba";

	// Here we just search upwards from the current directory, looking for a directory that
	// contains a file at the relative path "Animations/Animations.cba". This is designed to
	// handle root Game paths that differ from the default "Game".
	string rootDirCandidate = PathHelpers::GetDirectory(filePath);
	string rootDir;
	while (!rootDirCandidate.empty())
	{
		string cbaCandidatePath = PathHelpers::Join(rootDirCandidate, relativeCBAPath);
		if (PakSystemFile* file = pakSystem->Open(cbaCandidatePath.c_str(), "r"))
		{
			// File exists, we have found the correct root path.
			pakSystem->Close(file);

			rootDir = rootDirCandidate;
			break;
		}

		rootDirCandidate = PathHelpers::GetDirectory(rootDirCandidate);
	}

	return (rootDir.empty() ? rootDir : PathHelpers::Join(rootDir, relativeCBAPath));
}
