// ---------------------------------------------------------------------------
// 
//   Lily Engine alpha
// 
//   Copyright (c) 2010 Clifford Jolly
//     http://cliffjolly.com
//     cliff@cliffjolly.com
// 
// ---------------------------------------------------------------------------
// 
//   This program is free software; you can redistribute it and/or modify
//   it under the terms of the GNU General Public License as published by
//   the Free Software Foundation; either version 2 of the License, or
//   (at your option) any later version.
//  
//   This program is distributed in the hope that it will be useful, but
//   WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//   General Public License for more details.
// 
//   You should have received a copy of the GNU General Public License
//   along with this program; if not, write to the Free Software
//   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
//   USA
// -------------------------- END HEADER -------------------------------------

#include <iostream>
using namespace std;

#include "xmlstuff.h"
#include "../filesystem/filesystem.h"
#include "../console/console.h"
using namespace Console;

TiXmlDocument *loadXml(const std::string &fileName) {

	int fileLen;
	char *fileIn = FileSystem::loadFile(fileName, &fileLen);
	
	if(!fileIn) {
		// No file, couldn't load or something.
		out("error") << "Could not load XML file \"" << fileName << "\"." << endl;
		return NULL;
	}
	
	// Make a new buffer with enough room to stick an extra
	// null-terminator on the end.
	char *fileFixed = new char[fileLen + 1];
	
	// Copy it over and stick on the \0.
	memcpy(fileFixed, fileIn, fileLen);
	fileFixed[fileLen] = 0;
	
	// Clean up the old buffer.	
	delete[] fileIn;
	
	// Parse the XML.
	TiXmlBase::SetCondenseWhiteSpace(false);
	TiXmlDocument *doc = new TiXmlDocument();
	doc->Parse(fileFixed);
	
	// Clean up fixed buffer.
	delete[] fileFixed;
	
	if(doc->Error()) {
		// Woopsie.
		out("error") << "XML parse error: " << fileName << ":" << doc->ErrorRow() << "," << doc->ErrorCol() << " " << doc->ErrorDesc() << endl;
		delete doc;
		return NULL;
	}
	
	return doc;
}


