#include "GeometryReader.h"
#include "fileutils.h"
#include "OgreResourceManager.h"

namespace Ogre {

	GeometryReader::GeometryReader()
	{}
	GeometryReader::~GeometryReader()
	{}

	void GeometryReader::setFile(String file){
	}
	int GeometryReader::getGeometryDepth() const {
		return -1;
	}

	int GeometryReader::getVertexPosition(int x,int y,int level) const
	{
		int position = getLevelPosition(level)+((y*getLevelSize(level)+x)*getVertexSize());
		return position;
	}

	int GeometryReader::getLevelPosition(int level) const
	{
		int i;
		int position=0;
		for (i=0;i<level;i++){
			int levelsize = getLevelSize(i);
			position+=levelsize*levelsize*getVertexSize();
		}
		position+=getHeaderSize();
		return position;
	}


	Real GeometryReader::getLevelQuadSize(int level) const
	{
		int geoDepth = getGeometryDepth();
		if (geoDepth>level){
			return 1<<(geoDepth-level-1);
		} else {
			return 1/(Real)(1<<(level+1-geoDepth));
		}
	}

	void GeometryReader::openFile(String filename, FILE* &file)
	{

		FileInfoListPtr finfo =  ResourceGroupManager::getSingleton().findResourceFileInfo (
			String("ClipMap"), 
			filename);
		FileInfoList::iterator it = finfo->begin();
		assert (it != finfo->end());
	
		char *olddir = ChangeToDir (const_cast< char * > (((it)->archive->getName()).c_str()));

		file = fopen(filename.c_str(),"rb");
		assert (file);

		RetablishDir (olddir);
	
	}

	void GeometryReader::openFileForWriting(String filename, FILE* &file){
		FileInfoListPtr finfo =  ResourceGroupManager::getSingleton().findResourceFileInfo (
			String("ClipMap"), 
			filename);
		FileInfoList::iterator it = finfo->begin();
		assert (it != finfo->end());
		
		char *olddir = ChangeToDir (const_cast< char * > (((it)->archive->getName()).c_str()));

		file = fopen(filename.c_str(),"w+b");
		assert (file);

		RetablishDir (olddir);
		
	}


} // namespace Ogre
