#include "scenario.h"

extern PyObject* module;

void LoadMap(Map *map, const std::string& filename, float zoom)
{
	__scen_bullet scenbullets[50];
	int nextbullet=0;
	Uint32 ticks=SDL_GetTicks();
	Uint32 timepassed=0;
	Uint32 ms=0;
	Uint32 secs=0;
	Uint32 mins=0;
	Log::WriteVerbose("LoadMap() at ticks=%d",ticks);
	struct Local
	{
		static std::string getStringNode(DataNode* parent, const std::string& name)
		{
			DataNode* n = parent->getChild(name);
			return n->getString();
		}

		static int getIntNode(DataNode* parent, const std::string& name)
		{
			return atoi(getStringNode(parent, name).c_str());
		}
	};
	PHYSFS_file *fp=PHYSFS_openRead(filename.c_str());
	DataNode *rootNode=ReadDoc(fp);
	PHYSFS_close(fp);
	DataNode *realRoot = rootNode->getChild("fft-map");
	DataNode *infoNode = realRoot->getChild("information");
	std::string title=Local::getStringNode(infoNode, "title");

	DataNode* objectsNode = realRoot->getChild("objects");

	DataNodeList mapobjects = objectsNode->getChildren("mapobject");
	DataNodeList::iterator iter;
	if (!mapobjects.empty())
	{
		timepassed=SDL_GetTicks()-ticks;
		ms=timepassed%1000;
		secs=(unsigned int)((double)timepassed/1000.0);
		mins=(unsigned int)((double)secs/60.0);
		Log::WriteVerbose("Loading Map Objects, %d minutes, %d seconds, %d ms after LoadMap() begin", mins, secs, ms);
		for (iter = mapobjects.begin(); iter != mapobjects.end(); iter++)
		{
			std::string fpkname = Local::getStringNode(*iter, "fpk");
			float leastfpk = atof(Local::getStringNode(*iter, "fpkversion").c_str());
			float currentfpk = FPK_versionByName(fpkname);
			if (currentfpk<leastfpk)
			{
				char disp[300];
				sprintf(disp, "Scenario requires version %.2f of %s\nVersion found: %.2f", leastfpk, fpkname.c_str(), currentfpk);
				FPK_Invalid(fpkname, disp);
			}
			std::string fpk=FPK_ByName(fpkname);
			MapObject *object=new MapObject();
			std::string name = Local::getStringNode(*iter, "name");
			int x = Local::getIntNode(*iter, "x");
			int y = Local::getIntNode(*iter, "y");
			std::string imagefn = Local::getStringNode(*iter, "image");
			int mmr = Local::getIntNode(*iter, "mmr");
			int mmg = Local::getIntNode(*iter, "mmg");
			int mmb = Local::getIntNode(*iter, "mmb");
			if (mmr < 0 || mmr > 255) FPK_Invalid(fpkname, "FPK has a mapobject with an invalid mmr value");
			if (mmg < 0 || mmg > 255) FPK_Invalid(fpkname, "FPK has a mapobject with an invalid mmg value");
			if (mmb < 0 || mmb > 255) FPK_Invalid(fpkname, "FPK has a mapobject with an invalid mmb value");
			object->Init(x,y,imagefn,fpk,zoom);
			object->SetMMR(mmr);
			object->SetMMG(mmg);
			object->SetMMB(mmb);
			object->SetName(name);
			object->FreeImage();
			map->AddToObjects(object);
		}
		timepassed=SDL_GetTicks()-ticks;
		ms=timepassed%1000;
		secs=(unsigned int)((double)timepassed/1000.0);
		mins=(unsigned int)((double)secs/60.0);
		Log::WriteVerbose("Done Loading Map Objects, %d minutes, %d seconds, %d ms after LoadMap() begin", mins, secs, ms);
	}
	DataNodeList bullets = objectsNode->getChildren("bullet");
	if (!bullets.empty())
	{
		timepassed=SDL_GetTicks()-ticks;
		ms=timepassed%1000;
		secs=(unsigned int)((double)timepassed/1000.0);
		mins=(unsigned int)((double)secs/60.0);
		Log::WriteVerbose("Loading Bullets, %d minutes, %d seconds, %d ms after LoadMap() begin", mins, secs, ms);
		for (iter = bullets.begin(); iter != bullets.end(); iter++)
		{
			if (!(*iter)->hasChild("id")) SCN_Invalid(filename, "bullet under bullets is missing command 'id'");
			if (!(*iter)->hasChild("image")) SCN_Invalid(filename, "bullet under bullets is missing command 'image'");
			if (!(*iter)->hasChild("fpk")) SCN_Invalid(filename, "bullet under bullets is missing command 'fpk'");
			if (!(*iter)->hasChild("fpkversion")) SCN_Invalid(filename, "bullet under bullets is missing command 'fpkversion'");
			std::string fpkname = Local::getStringNode(*iter, "fpk");
			std::string fpk=FPK_ByName(fpkname);
			float leastfpk = atof(Local::getStringNode(*iter, "fpkversion").c_str());
			float currentfpk = FPK_versionByName(fpkname);
			if (currentfpk<leastfpk)
			{
				char disp[300];
				sprintf(disp, "Scenario requires version %.2f of %s\nVersion found: %.2f", leastfpk, fpkname.c_str(), currentfpk);
				FPK_Invalid(fpkname, disp);
			}
			scenbullets[nextbullet].id=Local::getIntNode(*iter, "id");
			scenbullets[nextbullet].fpk=fpk;
			scenbullets[nextbullet].imagefn=Local::getStringNode(*iter, "image");
			nextbullet++;
			//map->AddToBullets(fpk, Local::getStringNode(*iter, "image"), Local::getIntNode(*iter, "id"));
		}
		timepassed=SDL_GetTicks()-ticks;
		ms=timepassed%1000;
		secs=(unsigned int)((double)timepassed/1000.0);
		mins=(unsigned int)((double)secs/60.0);
		Log::WriteVerbose("Done Loading Bullets, %d minutes, %d seconds, %d ms after LoadMap() begin", mins, secs, ms);
	}
	DataNodeList actobjects = objectsNode->getChildren("actobject");
	if (!actobjects.empty())
	{
		timepassed=SDL_GetTicks()-ticks;
		ms=timepassed%1000;
		secs=(unsigned int)((double)timepassed/1000.0);
		mins=(unsigned int)((double)secs/60.0);
		Log::WriteVerbose("Loading Active Objects, %d minutes, %d seconds, %d ms after LoadMap() begin", mins, secs, ms);
		std::string imagefn;
		SDL_Surface *image=0;
		for (iter = actobjects.begin(); iter != actobjects.end(); iter++)
		{
			int count=1;
			if ((*iter)->hasChild("count")) count=Local::getIntNode(*iter, "count");
			int i;
			std::string fpkname = Local::getStringNode(*iter, "fpk");
			std::string fpk=FPK_ByName(fpkname);
			float leastfpk = atof(Local::getStringNode(*iter, "fpkversion").c_str());
			float currentfpk = FPK_versionByName(fpkname);
			if (currentfpk<leastfpk)
			{
				char disp[300];
				sprintf(disp, "Scenario requires version %.2f of %s\nVersion found: %.2f", leastfpk, fpkname.c_str(), currentfpk);
				FPK_Invalid(fpkname, disp);
			}
			std::string name = Local::getStringNode(*iter, "name");
			int x = Local::getIntNode(*iter, "x");
			int y = Local::getIntNode(*iter, "y");
			std::string newimagefn = Local::getStringNode(*iter, "image");
			if (strcmp(imagefn.c_str(),newimagefn.c_str()))
			{
				imagefn = Local::getStringNode(*iter, "image");
				if (image) SDL_FreeSurface(image);
				image=FPK_LoadIMG(fpk,imagefn);
			}
			int mmr = Local::getIntNode(*iter, "mmr");
			int mmg = Local::getIntNode(*iter, "mmg");
			int mmb = Local::getIntNode(*iter, "mmb");
			if (mmr < 0 || mmr > 255) FPK_Invalid(fpkname, "FPK has an active object with an invalid mmr value");
			if (mmg < 0 || mmg > 255) FPK_Invalid(fpkname, "FPK has an active object with an invalid mmg value");
			if (mmb < 0 || mmb > 255) FPK_Invalid(fpkname, "FPK has an active object with an invalid mmb value");
			int credits = Local::getIntNode(*iter, "credits");
			int maxhit=1;
			if ((*iter)->hasChild("maxhit")) maxhit = Local::getIntNode(*iter, "maxhit");
			if (maxhit<1) maxhit=1;
			int speed=0;
			int orbitx=0;
			int orbity=0;
			int distance=0;
			for (i=0; i<count; i++)
			{
				if ((*iter)->hasChild("speed"))
				{
					if ((*iter)->getChild("speed")->hasChild("random"))
					{
						int val1=Local::getIntNode((*iter)->getChild("speed")->getChild("random"), "val1");
						int val2=Local::getIntNode((*iter)->getChild("speed")->getChild("random"), "val2");
						speed=(rand()%(val2-val1))+val1;
					}
					else
					{
						speed=Local::getIntNode(*iter, "speed");
					}
				}
				if ((*iter)->hasChild("orbit"))
				{
					orbitx=Local::getIntNode(*iter, "x");
					orbity=Local::getIntNode(*iter, "y");
					if ((*iter)->getChild("orbit")->getChild("distance")->hasChild("random"))
					{
						int val1=Local::getIntNode((*iter)->getChild("orbit")->getChild("distance")->getChild("random"), "val1");
						int val2=Local::getIntNode((*iter)->getChild("orbit")->getChild("distance")->getChild("random"), "val2");
						distance=(rand()%(val2-val1))+val1;
					}
					else
					{
						distance=Local::getIntNode((*iter)->getChild("orbit"), "distance");
					}
				}
				Unit *object=new Unit();
				object->Init(x,y,imagefn,image,fpk,zoom);
				object->SetName(name);
				object->SetSpeed(speed);
				object->SetHullHitMax(maxhit);
				object->SetMMR(mmr);
				object->SetMMG(mmg);
				object->SetMMB(mmb);
				object->SetCredits((unsigned int)credits);
				if (orbitx||orbity||distance)
				{
					object->SetOrbit(true);
					object->Orbit(orbitx,orbity,distance);
				}
				object->FreeImages();
				map->AddToActiveObjects(object);
			}
		}
		if (image) SDL_FreeSurface(image);
		timepassed=SDL_GetTicks()-ticks;
		ms=timepassed%1000;
		secs=(unsigned int)((double)timepassed/1000.0);
		mins=(unsigned int)((double)secs/60.0);
		Log::WriteVerbose("Done Loading Active Objects, %d minutes, %d seconds, %d ms after LoadMap() begin", mins, secs, ms);
	}
	DataNodeList aiships = objectsNode->getChildren("aiship");
	if (!aiships.empty())
	{
		timepassed=SDL_GetTicks()-ticks;
		ms=timepassed%1000;
		secs=(unsigned int)((double)timepassed/1000.0);
		mins=(unsigned int)((double)secs/60.0);
		Log::WriteVerbose("Loading AI Ships, %d minutes, %d seconds, %d ms after LoadMap() begin", mins, secs, ms);
		for (iter = aiships.begin(); iter != aiships.end(); iter++)
		{
			std::string fpkname = Local::getStringNode(*iter, "fpk");
			std::string fpk=FPK_ByName(fpkname);
			float leastfpk = atof(Local::getStringNode(*iter, "fpkversion").c_str());
			float currentfpk = FPK_versionByName(fpkname);
			if (currentfpk<leastfpk)
			{
				char disp[300];
				sprintf(disp, "Scenario requires version %.2f of %s\nVersion found: %.2f", leastfpk, fpkname.c_str(), currentfpk);
				FPK_Invalid(fpkname, disp);
			}
			Unit *object=new Unit();
			std::string name = Local::getStringNode(*iter, "name");
			int x = Local::getIntNode(*iter, "x");
			int y = Local::getIntNode(*iter, "y");
			std::string imagefn = Local::getStringNode(*iter, "image");
			int mmr = Local::getIntNode(*iter, "mmr");
			int mmg = Local::getIntNode(*iter, "mmg");
			int mmb = Local::getIntNode(*iter, "mmb");
			if (mmr < 0 || mmr > 255) FPK_Invalid(fpkname, "FPK has an aiship with an invalid mmr value");
			if (mmg < 0 || mmg > 255) FPK_Invalid(fpkname, "FPK has an aiship with an invalid mmg value");
			if (mmb < 0 || mmb > 255) FPK_Invalid(fpkname, "FPK has an aiship with an invalid mmb value");
			int credits = Local::getIntNode(*iter, "credits");
			int cr=0;
			int cg=0;
			int cb=0;
			if ((*iter)->hasChild("color"))
			{
				cr=Local::getIntNode((*iter)->getChild("color"), "r");
				cg=Local::getIntNode((*iter)->getChild("color"), "g");
				cb=Local::getIntNode((*iter)->getChild("color"), "b");
				if (cr < 0 || cr > 255) FPK_Invalid(fpkname, "FPK has an aiship with an invalid r value under 'color'");
				if (cg < 0 || cg > 255) FPK_Invalid(fpkname, "FPK has an aiship with an invalid g value under 'color'");
				if (cb < 0 || cb > 255) FPK_Invalid(fpkname, "FPK has an aiship with an invalid b value under 'color'");
			}
			__ship_slot s_slots[__MAXSHIPSLOTS];
			int slotnext=0;
			DataNodeList slots = (*iter)->getChildren("slot");
			if (!slots.empty())
			{
				DataNodeList::iterator iter2;
				for (iter2 = slots.begin(); iter2 != slots.end(); iter2++)
				{
					if (!(*iter2)->hasChild("id")) FPK_Invalid(fpkname, "slot found with no id on an aiship");
					if (!(*iter2)->hasChild("w")) FPK_Invalid(fpkname, "slot found with no 'w' command on an aiship");
					if (!(*iter2)->hasChild("l")) FPK_Invalid(fpkname, "slot found with no 'l' command on an aiship");
					if (!(*iter2)->hasChild("d")) FPK_Invalid(fpkname, "slot found with no 'd' command on an aiship");
					if (!(*iter2)->hasChild("type")) FPK_Invalid(fpkname, "slot found with no type on an aiship");
					s_slots[slotnext].id=Local::getIntNode((*iter2),"id");
					s_slots[slotnext].w=Local::getIntNode((*iter2),"w");
					s_slots[slotnext].l=Local::getIntNode((*iter2),"l");
					s_slots[slotnext].d=Local::getIntNode((*iter2),"d");
					s_slots[slotnext].type=Local::getStringNode((*iter2),"type");
					s_slots[slotnext].image=0;
					if ((*iter2)->hasChild("holdamount")) s_slots[slotnext].holdamount=Local::getIntNode((*iter2),"holdamount");
					slotnext++;
				}
			}
			int maxspeed = Local::getIntNode(*iter, "maxspeed");
			int hullhitmax = Local::getIntNode(*iter, "hullhitmax");
			std::string saistate = Local::getStringNode(*iter, "aistate");
			int aistate=0;
			if (!strcmp(saistate.c_str(),"AI_STATE_STOP")) aistate=AI_STATE_STOP;
			else if (!strcmp(saistate.c_str(),"AI_STATE_RUN")) aistate=AI_STATE_RUN;
			else if (!strcmp(saistate.c_str(),"AI_STATE_ATTACK")) aistate=AI_STATE_ATTACK;
			else if (!strcmp(saistate.c_str(),"AI_STATE_LOOK")) aistate=AI_STATE_LOOK;
			else if (!strcmp(saistate.c_str(),"AI_STATE_IGNORE")) aistate=AI_STATE_IGNORE;
			else if (!strcmp(saistate.c_str(),"AI_STATE_WAITLOOK")) aistate=AI_STATE_WAITLOOK;
			object->Init(x,y,imagefn,fpk,zoom);
			object->ZeroSlots();
			object->FillSlots(s_slots, slotnext);
			if (!slots.empty())
			{
				//check for the proper id, and fill it up with ammo if necessary.
				//Also do error checking
				DataNodeList::iterator iter2;
				for (iter2 = slots.begin(); iter2 != slots.end(); iter2++)
				{
					if ((*iter2)->hasChild("bulletfill"))
					{
						int i;
						bool idfound=false;
						if (!(*iter2)->hasChild("ammofill")) FPK_Invalid(fpkname, "slot found with no 'ammofill' command on an aiship (must at least be 0)");
						int bulletid=Local::getIntNode((*iter2),"bulletfill");
						for (i=0; i<nextbullet; i++)
						{
							if (scenbullets[i].id==bulletid)
							{
								idfound=true;
								int ammo=0;
								int tempammo=Local::getIntNode((*iter2),"ammofill");
								if (tempammo>0) ammo=tempammo;
								object->AddWeaponToSlot(Local::getIntNode((*iter2),"id"), scenbullets[i].fpk, scenbullets[i].imagefn, ammo);
								break;
							}
						}
						if (!idfound) FPK_Invalid(fpkname, "slot has a bulletfill command with an invalid id");
					}
				}
			}
			object->SetName(name);
			object->SetMMR(mmr);
			object->SetMMG(mmg);
			object->SetMMB(mmb);
			object->SetCredits((unsigned int)credits);
			object->SetMaxSpeed(maxspeed);
			object->SetHullHitMax(hullhitmax);
			object->SetAIState(aistate);
			object->SetAI(Local::getStringNode(*iter, "aiscript"));
			if (cr||cg||cb) object->Colorize(cr,cg,cb);
			object->FreeImages();
			map->AddToUnits(object);
		}
		timepassed=SDL_GetTicks()-ticks;
		ms=timepassed%1000;
		secs=(unsigned int)((double)timepassed/1000.0);
		mins=(unsigned int)((double)secs/60.0);
		Log::WriteVerbose("Done Loading AI Ships, %d minutes, %d seconds, %d ms after LoadMap() begin", mins, secs, ms);
	}
	DataNodeList stations = objectsNode->getChildren("station");
	if (!stations.empty())
	{
		timepassed=SDL_GetTicks()-ticks;
		ms=timepassed%1000;
		secs=(unsigned int)((double)timepassed/1000.0);
		mins=(unsigned int)((double)secs/60.0);
		Log::WriteVerbose("Loading Stations, %d minutes, %d seconds, %d ms after LoadMap() begin", mins, secs, ms);
		for (iter = stations.begin(); iter != stations.end(); iter++)
		{
			std::string fpkname = Local::getStringNode(*iter, "fpk");
			float leastfpk = atof(Local::getStringNode(*iter, "fpkversion").c_str());
			float currentfpk = FPK_versionByName(fpkname);
			if (currentfpk<leastfpk)
			{
				char disp[300];
				sprintf(disp, "Scenario requires version %.2f of %s\nVersion found: %.2f", leastfpk, fpkname.c_str(), currentfpk);
				FPK_Invalid(fpkname, disp);
			}
			std::string fpk=FPK_ByName(fpkname);
			Station *object=new Station();
			std::string name = Local::getStringNode(*iter, "name");
			int x = Local::getIntNode(*iter, "x");
			int y = Local::getIntNode(*iter, "y");
			std::string imagefn = Local::getStringNode(*iter, "image");
			int mmr = Local::getIntNode(*iter, "mmr");
			int mmg = Local::getIntNode(*iter, "mmg");
			int mmb = Local::getIntNode(*iter, "mmb");
			if (mmr < 0 || mmr > 255) FPK_Invalid(fpkname, "FPK has a station with an invalid mmr value");
			if (mmg < 0 || mmg > 255) FPK_Invalid(fpkname, "FPK has a station with an invalid mmg value");
			if (mmb < 0 || mmb > 255) FPK_Invalid(fpkname, "FPK has a station with an invalid mmb value");
			object->Init(x,y,imagefn,fpk,zoom);
			object->SetMMR(mmr);
			object->SetMMG(mmg);
			object->SetMMB(mmb);
			object->SetName(name);
			object->FreeImage();
			if ((*iter)->hasChild("shop"))
			{
				if ((*iter)->getChild("shop")->hasChild("buy"))
				{
					DataNodeList items=(*iter)->getChild("shop")->getChild("buy")->getChildren("item");
					DataNodeList::iterator iter2;
					if (!items.empty())
					{
						for (iter2 = items.begin(); iter2 != items.end(); iter2++)
						{
							if (!((*iter2)->hasChild("type"))) SCN_Invalid(filename,"Map file contains an item with no type");
							if (!((*iter2)->hasChild("name"))) SCN_Invalid(filename,"Map file contains an item with no name");
							std::string fpk;
							if ((*iter2)->hasChild("dispimage") || (*iter2)->hasChild("image"))
							{
								std::string fpkname = Local::getStringNode(*iter2, "fpk");
								fpk=FPK_ByName(fpkname);
								float leastfpk = atof(Local::getStringNode(*iter2, "fpkversion").c_str());
								float currentfpk = FPK_versionByName(fpkname);
								if (currentfpk<leastfpk)
								{
									char disp[300];
									sprintf(disp, "Scenario requires version %.2f of %s\nVersion found: %.2f", leastfpk, fpkname.c_str(), currentfpk);
									FPK_Invalid(fpkname, disp);
								}
							}
							__shopitem item;
							item.type=Local::getStringNode(*iter2, "type");
							item.fpk=fpk;
							if ((*iter2)->hasChild("baytype")) item.baytype=Local::getStringNode(*iter2, "baytype");
							if ((*iter2)->hasChild("holdweapon")) item.holdweapon=Local::getStringNode(*iter2, "holdweapon");
							if ((*iter2)->hasChild("ammotype")) item.holdweapon=Local::getStringNode(*iter2, "ammotype");
							if ((*iter2)->hasChild("amount")) item.amount=Local::getIntNode(*iter2, "amount");
							else item.amount=0;
							if ((*iter2)->hasChild("holdamount")) item.holdamount=Local::getIntNode(*iter2, "holdamount");
							else item.holdamount=0;
							if ((*iter2)->hasChild("cargounits")) item.cargounits=Local::getIntNode(*iter2, "cargounits");
							else item.cargounits=0;
							item.name=Local::getStringNode(*iter2, "name");
							if ((*iter2)->hasChild("description")) item.desc=Local::getStringNode(*iter2, "description");
							if ((*iter2)->hasChild("price"))
							{
								item.baseprice=0;
								item.price=Local::getIntNode(*iter2, "price");
							}
							else if ((*iter2)->hasChild("baseprice"))
							{
								item.baseprice=Local::getIntNode(*iter2, "baseprice");
								item.price=Local::getIntNode(*iter2, "baseprice");
							}
							else SCN_Invalid(filename,"Map file contains an item with no price or baseprice");
							if ((*iter2)->hasChild("dispimage")) item.dispimage=FPK_LoadIMG(fpk,Local::getStringNode(*iter2, "dispimage"));
							else item.dispimage=0;
							if ((*iter2)->hasChild("image")) item.imagefn=Local::getStringNode(*iter2, "image");
							if ((*iter2)->hasChild("baseimport")) item.baseimport=Local::getIntNode(*iter2, "baseimport");
							else item.baseimport=0;
							if ((*iter2)->hasChild("w") && !strcmp(item.type.c_str(),"bay")) item.bayw=Local::getIntNode(*iter2, "w");
							else item.bayw=0;
							if ((*iter2)->hasChild("l") && !strcmp(item.type.c_str(),"bay")) item.bayl=Local::getIntNode(*iter2, "l");
							else item.bayl=0;
							if ((*iter2)->hasChild("d") && !strcmp(item.type.c_str(),"bay")) item.bayd=Local::getIntNode(*iter2, "d");
							else item.bayd=0;
							object->AddItemToBuyShop(item);
						}
					}
				}
				if ((*iter)->getChild("shop")->hasChild("sell"))
				{
					DataNodeList items=(*iter)->getChild("shop")->getChild("sell")->getChildren("item");
					DataNodeList::iterator iter2;
					if (!items.empty())
					{
						for (iter2 = items.begin(); iter2 != items.end(); iter2++)
						{
							if (!((*iter2)->hasChild("name"))) SCN_Invalid(filename,"Map file contains an item with no name");
							//std::string fpk;
							std::string type=Local::getStringNode(*iter2, "type");
							if (!strcmp(type.c_str(),"cargo"))
							{
								__cargo cargo;
								cargo.type=Local::getStringNode(*iter2, "name");
								if ((*iter2)->hasChild("price"))
								{
									cargo.priceBought=Local::getIntNode(*iter2, "price");
								}
								else if ((*iter2)->hasChild("baseprice"))
								{
									cargo.priceBought=Local::getIntNode(*iter2, "baseprice");
								}
								object->AddSellableCargo(cargo);
							}
						}
					}
				}
				if ((*iter)->hasChild("repairs"))
				{
					if ((*iter)->getChild("repairs")->hasChild("shields"))
					{
						if (!(*iter)->getChild("repairs")->getChild("shields")->hasChild("baseprice")) SCN_Invalid(filename, "shield repairs found, but no baseprice command found");
						unsigned int cost=Local::getIntNode((*iter)->getChild("repairs")->getChild("shields"), "baseprice");
						object->AllowShieldRepairs(cost);
					}
					if ((*iter)->getChild("repairs")->hasChild("hull"))
					{
						if (!(*iter)->getChild("repairs")->getChild("hull")->hasChild("baseprice")) SCN_Invalid(filename, "hull repairs found, but no baseprice command found");
						unsigned int cost=Local::getIntNode((*iter)->getChild("repairs")->getChild("hull"), "baseprice");
						object->AllowHullRepairs(cost);
					}
				}
				if ((*iter)->hasChild("shipyard"))
				{
					DataNodeList ships=(*iter)->getChild("shipyard")->getChildren("ship");
					DataNodeList::iterator iter2;
					if (!ships.empty())
					{
						for (iter2 = ships.begin(); iter2 != ships.end(); iter2++)
						{
							if (!((*iter2)->hasChild("name"))) SCN_Invalid(filename,"Map file contains a ship with no name");
							if (!((*iter2)->hasChild("fpk"))) SCN_Invalid(filename,"Map file contains a ship with no fpk");
							std::string shipname=Local::getStringNode(*iter2, "name");
							std::string fpkname = Local::getStringNode(*iter2, "fpk");
							std::string fpk;
							fpk=FPK_ByName(fpkname);
							FPKShip *ship=new FPKShip(fpk, shipname);
							object->AddShipToShipyard(ship);
						}
						object->InitShipyardShop();
					}
				}
			}
			map->AddToStations(object);
		}
		timepassed=SDL_GetTicks()-ticks;
		ms=timepassed%1000;
		secs=(unsigned int)((double)timepassed/1000.0);
		mins=(unsigned int)((double)secs/60.0);
		Log::WriteVerbose("Done Loading Stations, %d minutes, %d seconds, %d ms after LoadMap() begin", mins, secs, ms);
	}
	Log::WriteVerbose("Loading Animations");
	StaticAnim *anim=new StaticAnim;
	anim->LoadFrames("gfx/anim/explosion");
	map->AddToAnimations(anim);
	timepassed=SDL_GetTicks()-ticks;
	ms=timepassed%1000;
	secs=(unsigned int)((double)timepassed/1000.0);
	mins=(unsigned int)((double)secs/60.0);
	Log::WriteVerbose("Done Loading Map, %d minutes, %d seconds, %d ms total", mins, secs, ms);
	delete rootNode;
}

void Scenario::Init(std::string fn, Map *map)
{
	this->SetMap(map);
	this->ReadOnly(fn);
}
void Scenario::ReadOnly(std::string fn)
{
	startx=0;
	starty=0;
	startang=0;
	startspeed=0;
	credits=0;
	startingshipnext=0;
	//int i;
	/*
	for (i=0; i<50; i++)
	{
		get[i]=false;
		got[i]=false;
	}
	*/
	struct Local
	{
		static std::string getStringNode(DataNode* parent, const std::string& name)
		{
			DataNode* n = parent->getChild(name);
			return n->getString();
		}

		static int getIntNode(DataNode* parent, const std::string& name)
		{
			return atoi(getStringNode(parent, name).c_str());
		}
	};
	file=fn;
	PHYSFS_file *fp=PHYSFS_openRead(file.c_str());
	DataNode *rootNode=ReadDoc(fp);
	PHYSFS_close(fp);
	if (!rootNode->hasChild("fft-scn")) SCN_Invalid(file, "File is not a valid Scenario file");
	DataNode *realRoot = rootNode->getChild("fft-scn");
	if (!realRoot->hasChild("information")) SCN_Invalid(file, "information block not found in Scenario file");
	if (!realRoot->getChild("information")->hasChild("title")) SCN_Invalid(file, "title command not found in information block");
	if (!realRoot->getChild("information")->hasChild("description")) SCN_Invalid(file, "description command not found in information block");
	name=Local::getStringNode(realRoot->getChild("information"), "title");
	desc=Local::getStringNode(realRoot->getChild("information"), "description");
	if (!realRoot->hasChild("mapfile")) SCN_Invalid(name, "mapfile command not found in Scenario file");
	mapfn="scenario/";
	mapfn+=Local::getStringNode(realRoot, "mapfile");
	if (!realRoot->hasChild("openmessage")) SCN_Invalid(name, "openmessage command not found in Scenario file");
	openmessage=Local::getStringNode(realRoot, "openmessage");
	if (realRoot->hasChild("module")) modulename=Local::getStringNode(realRoot, "module");
	DataNodeList::iterator iter;
	//if (!realRoot->hasChild("victory")) SCN_Invalid(name, "victory command not found in Scenario file");
	/*
	DataNode *victoryNode = realRoot->getChild("victory");
	DataNodeList conditionsets = victoryNode->getChildren("conditionset");
	if (!conditionsets.empty())
	{
		for (iter = conditionsets.begin(); iter != conditionsets.end(); iter++)
		{
			if ((*iter)->hasChild("actobjects"))
			{
				conditionset[victnext]=condnext;
				if ((*iter)->hasChild("meet"))
				{
					meet[victnext]=Local::getIntNode(*iter, "meet");
				}
				else SCN_Invalid(name, "actobjects victory condition has no 'meet' command");
				if ((*iter)->getChild("actobjects")->hasChild("whenmet"))
				{
					get[victnext]=true;
					getwhat[victnext]=Local::getStringNode((*iter)->getChild("actobjects"), "whenmet");
				}
				valvictory[victnext] = "actobjects";
				if ((*iter)->getChild("actobjects")->hasChild("equals"))
				{
					victory[victnext] = Local::getIntNode((*iter)->getChild("actobjects"), "equals");
					compvictory[victnext] = "equals";
					victnext++;
				}
				else if ((*iter)->getChild("actobjects")->hasChild("notequal"))
				{
					victory[victnext] = Local::getIntNode((*iter)->getChild("actobjects"), "notequal");
					compvictory[victnext] = "notequal";
					victnext++;
				}
				else if ((*iter)->getChild("actobjects")->hasChild("lessthan"))
				{
					victory[victnext] = Local::getIntNode((*iter)->getChild("actobjects"), "lessthan");
					compvictory[victnext] = "lessthan";
					victnext++;
				}
				else if ((*iter)->getChild("actobjects")->hasChild("greaterthan"))
				{
					victory[victnext] = Local::getIntNode((*iter)->getChild("actobjects"), "greaterthan");
					compvictory[victnext] = "greaterthan";
					victnext++;
				}
				else if ((*iter)->getChild("actobjects")->hasChild("lessthanorequal"))
				{
					victory[victnext] = Local::getIntNode((*iter)->getChild("actobjects"), "lessthanorequal");
					compvictory[victnext] = "lessthanorequal";
					victnext++;
				}
				else if ((*iter)->getChild("actobjects")->hasChild("greaterthanorequal"))
				{
					victory[victnext] = Local::getIntNode((*iter)->getChild("actobjects"), "greaterthanorequal");
					compvictory[victnext] = "greaterthanorequal";
					victnext++;
				}
				else SCN_Invalid(name, "actobjects victory condition has no valid command");
			}
			if ((*iter)->hasChild("aiships"))
			{
				conditionset[victnext]=condnext;
				if ((*iter)->hasChild("meet"))
				{
					meet[victnext]=Local::getIntNode(*iter, "meet");
				}
				else SCN_Invalid(name, "aiships victory condition has no 'meet' command");
				if ((*iter)->getChild("aiships")->hasChild("whenmet"))
				{
					get[victnext]=true;
					getwhat[victnext]=Local::getStringNode((*iter)->getChild("aiships"), "whenmet");
				}
				valvictory[victnext] = "aiships";
				if ((*iter)->getChild("aiships")->hasChild("equals"))
				{
					victory[victnext] = Local::getIntNode((*iter)->getChild("aiships"), "equals");
					compvictory[victnext] = "equals";
					victnext++;
				}
				else if ((*iter)->getChild("aiships")->hasChild("notequal"))
				{
					victory[victnext] = Local::getIntNode((*iter)->getChild("aiships"), "notequal");
					compvictory[victnext] = "notequal";
					victnext++;
				}
				else if ((*iter)->getChild("aiships")->hasChild("lessthan"))
				{
					victory[victnext] = Local::getIntNode((*iter)->getChild("aiships"), "lessthan");
					compvictory[victnext] = "lessthan";
					victnext++;
				}
				else if ((*iter)->getChild("aiships")->hasChild("greaterthan"))
				{
					victory[victnext] = Local::getIntNode((*iter)->getChild("aiships"), "greaterthan");
					compvictory[victnext] = "greaterthan";
					victnext++;
				}
				else if ((*iter)->getChild("aiships")->hasChild("lessthanorequal"))
				{
					victory[victnext] = Local::getIntNode((*iter)->getChild("aiships"), "lessthanorequal");
					compvictory[victnext] = "lessthanorequal";
					victnext++;
				}
				else if ((*iter)->getChild("aiships")->hasChild("greaterthanorequal"))
				{
					victory[victnext] = Local::getIntNode((*iter)->getChild("aiships"), "greaterthanorequal");
					compvictory[victnext] = "greaterthanorequal";
					victnext++;
				}
				else SCN_Invalid(name, "aiships victory condition has no valid command");
			}
			condnext++;
		}
	}
	else SCN_Invalid(name, "No 'conditionset's found under victory command");
	if (realRoot->hasChild("loss"))
	{
		DataNode *lossNode = realRoot->getChild("loss");
		DataNodeList conditionsets2 = lossNode->getChildren("conditionset");
		if (!conditionsets2.empty())
		{
			for (iter = conditionsets2.begin(); iter != conditionsets2.end(); iter++)
			{
				if ((*iter)->hasChild("actobjects"))
				{
					lconditionset[lossnext]=lcondnext;
					if ((*iter)->hasChild("meet"))
					{
						lmeet[lossnext]=Local::getIntNode(*iter, "meet");
					}
					else SCN_Invalid(name, "actobjects loss condition has no 'meet' command");
					valloss[lossnext] = "actobjects";
					if ((*iter)->getChild("actobjects")->hasChild("equals"))
					{
						loss[lossnext] = Local::getIntNode((*iter)->getChild("actobjects"), "equals");
						comploss[lossnext] = "equals";
						lossnext++;
					}
					else if ((*iter)->getChild("actobjects")->hasChild("notequal"))
					{
						loss[lossnext] = Local::getIntNode((*iter)->getChild("actobjects"), "notequal");
						comploss[lossnext] = "notequal";
						lossnext++;
					}
					else if ((*iter)->getChild("actobjects")->hasChild("lessthan"))
					{
						loss[lossnext] = Local::getIntNode((*iter)->getChild("actobjects"), "lessthan");
						comploss[lossnext] = "lessthan";
						lossnext++;
					}
					else if ((*iter)->getChild("actobjects")->hasChild("greaterthan"))
					{
						loss[lossnext] = Local::getIntNode((*iter)->getChild("actobjects"), "greaterthan");
						comploss[lossnext] = "greaterthan";
						lossnext++;
					}
					else if ((*iter)->getChild("actobjects")->hasChild("lessthanorequal"))
					{
						loss[lossnext] = Local::getIntNode((*iter)->getChild("actobjects"), "lessthanorequal");
						comploss[lossnext] = "lessthanorequal";
						lossnext++;
					}
					else if ((*iter)->getChild("actobjects")->hasChild("greaterthanorequal"))
					{
						loss[lossnext] = Local::getIntNode((*iter)->getChild("actobjects"), "greaterthanorequal");
						comploss[lossnext] = "greaterthanorequal";
						lossnext++;
					}
					else SCN_Invalid(name, "actobjects loss condition has no valid command");
				}
				if ((*iter)->hasChild("aiships"))
				{
					lconditionset[lossnext]=lcondnext;
					if ((*iter)->hasChild("meet"))
					{
						lmeet[lossnext]=Local::getIntNode(*iter, "meet");
					}
					else SCN_Invalid(name, "aiships loss condition has no 'meet' command");
					valloss[lossnext] = "aiships";
					if ((*iter)->getChild("aiships")->hasChild("equals"))
					{
						loss[lossnext] = Local::getIntNode((*iter)->getChild("aiships"), "equals");
						comploss[lossnext] = "equals";
						lossnext++;
					}
					else if ((*iter)->getChild("aiships")->hasChild("notequal"))
					{
						loss[lossnext] = Local::getIntNode((*iter)->getChild("aiships"), "notequal");
						comploss[lossnext] = "notequal";
						lossnext++;
					}
					else if ((*iter)->getChild("aiships")->hasChild("lessthan"))
					{
						loss[lossnext] = Local::getIntNode((*iter)->getChild("aiships"), "lessthan");
						comploss[lossnext] = "lessthan";
						lossnext++;
					}
					else if ((*iter)->getChild("aiships")->hasChild("greaterthan"))
					{
						loss[lossnext] = Local::getIntNode((*iter)->getChild("aiships"), "greaterthan");
						comploss[lossnext] = "greaterthan";
						lossnext++;
					}
					else if ((*iter)->getChild("aiships")->hasChild("lessthanorequal"))
					{
						loss[lossnext] = Local::getIntNode((*iter)->getChild("aiships"), "lessthanorequal");
						comploss[lossnext] = "lessthanorequal";
						lossnext++;
					}
					else if ((*iter)->getChild("aiships")->hasChild("greaterthanorequal"))
					{
						loss[lossnext] = Local::getIntNode((*iter)->getChild("aiships"), "greaterthanorequal");
						comploss[lossnext] = "greaterthanorequal";
						lossnext++;
					}
					else SCN_Invalid(name, "aiships loss condition has no valid command");
				}
				lcondnext++;
			}
		}
		else SCN_Invalid(name, "No 'conditionset's found under loss command");
	}
	*/
	if (!realRoot->hasChild("start")) SCN_Invalid(name, "start command not found in Scenario file");
	if (!realRoot->getChild("start")->hasChild("x")) SCN_Invalid(name, "start command does not have x command");
	if (!realRoot->getChild("start")->hasChild("y")) SCN_Invalid(name, "start command does not have y command");
	if (!realRoot->getChild("start")->hasChild("angle")) SCN_Invalid(name, "start command does not have angle command");
	if (!realRoot->getChild("start")->hasChild("speed")) SCN_Invalid(name, "start command does not have speed command");
	if (!realRoot->getChild("start")->hasChild("credits")) SCN_Invalid(name, "start command does not have credits command");
	if (realRoot->getChild("start")->hasChild("disablewarp")) disablewarp=true;
	else disablewarp=false;
	startx=Local::getIntNode(realRoot->getChild("start"), "x");
	starty=Local::getIntNode(realRoot->getChild("start"), "y");
	startang=((Local::getIntNode(realRoot->getChild("start"), "angle"))/5);
	startang=(startang*5)%360;
	startspeed=Local::getIntNode(realRoot->getChild("start"), "speed");
	credits=Local::getIntNode(realRoot->getChild("start"), "credits");
	if (!realRoot->hasChild("startingships")) SCN_Invalid(name, "startingships command not found in Scenario file");
	DataNodeList ships = realRoot->getChild("startingships")->getChildren("ship");
	if (!ships.empty())
	{
		for (iter = ships.begin(); iter != ships.end(); iter++)
		{
			if (!(*iter)->hasChild("name")) SCN_Invalid(name, "ship under starting ships is missing command 'name'");
			if (!(*iter)->hasChild("fpk")) SCN_Invalid(name, "ship under starting ships is missing command 'fpk'");
			startingshipnames[startingshipnext]=Local::getStringNode(*iter, "name");
			startingshipfpks[startingshipnext]=Local::getStringNode(*iter, "fpk");
			startingshipnext++;
		}
	}
	delete rootNode;
}
void Scenario::SetMap(Map *map)
{
	scnmap=map;
}
void Scenario::Startup()
{
	if (disablewarp) scnmap->mainship->DisableWarp();
	else scnmap->mainship->EnableWarp();
}
bool Scenario::CheckVictory()
{
	PyObject *pDict = PyModule_GetDict(module);  //get the dict of the module (listing of all symbols in there),
	PyObject *pFunc = PyDict_GetItemString(pDict, "Victory");
	PyObject *test=PyObject_CallFunction(pFunc, 0);
	if(PyObject_IsTrue(test)) return true;
	else return false;
}
bool Scenario::CheckLoss()
{
	PyObject *pDict = PyModule_GetDict(module);  //get the dict of the module (listing of all symbols in there),
	PyObject *pFunc = PyDict_GetItemString(pDict, "Loss");
	PyObject *test=PyObject_CallFunction(pFunc, 0);
	if(PyObject_IsTrue(test)) return true;
	else return false;
}
std::string Scenario::GetMapFn()
{
	return mapfn;
}
std::string Scenario::GetName()
{
	return name;
}
std::string Scenario::GetDesc()
{
	return desc;
}
std::string Scenario::GetOpenMessage()
{
	return openmessage;
}
std::string Scenario::GetModuleName()
{
	return modulename;
}
int Scenario::GetStartX()
{
	return startx;
}
int Scenario::GetStartY()
{
	return starty;
}
int Scenario::GetStartAngle()
{
	return startang;
}
int Scenario::GetStartSpeed()
{
	return startspeed;
}
unsigned int Scenario::GetStartCredits()
{
	return credits;
}
bool Scenario::ShipIsAllowed(std::string name, std::string fpk)
{
	int i;
	if (startingshipnext)
	{
		for(i=0; i<startingshipnext; i++)
		{
			if (!strcmp(name.c_str(), startingshipnames[i].c_str()) && !strcmp(fpk.c_str(), FPK_ByName(startingshipfpks[i]).c_str()))
			{
				return true;
			}
		}
	}
	else return true;
	return false;
}

bool IsScenario(char *str)
{
	unsigned int start=strlen(str)-8;
	char temp[9];
	unsigned int i;
	for(i=0; i<strlen(str)-start; i++)
	{
		temp[i]=str[i+start];
	}
	temp[8]='\0';
	if (!strcmp(temp,".fft-scn")) return true;
	else return false;
}
std::string ChooseScenario()
{
	SDL_Event event;
	SDL_Surface *screen=SDL_GetVideoSurface();
	int w=screen->w;
	int h=screen->h;
	GUI *sGUI=new GUI;
	SDL_Color white = { 0xFF, 0xFF, 0xFF, 0 };
	TTF_Font *font=TTF_OpenFont("fonts/arial.ttf", 12);
	TTF_Font *font14=TTF_OpenFont("fonts/arial.ttf", 14);
	char **scnlist;
	char **k;
	std::string retval;
	sGUI->Init();
	sGUI->MakeWindow(30, h-80, 50, 34);
	sGUI->MakeWindow(w/2-60, h-80, 120, 34);
	sGUI->MakeWindow(w/2-55, h-45, 110, 34);
	sGUI->MakeWindow(w-80, h-80, 50, 34);
	int prev=sGUI->MakeButton(35, h-75, 40, "< Prev");
	int select=sGUI->MakeButton(w/2-55, h-75, 110, "Select this Scenario");
	int back=sGUI->MakeButton(w/2-50, h-40, 100, "Back to Main Menu");
	int next=sGUI->MakeButton(w-75, h-75, 40, "Next >");
	int done=0;

	//if there is an order file, order the scenarios accordingly
	const int total=100;
	std::string scen[total];
	std::string name[total];
	std::string desc[total];
	std::string module[total];
	DataNode *rootNode=0;
	DataNodeList orderedScenarios;
	DataNodeList::iterator iter;
	PHYSFS_file *fp=PHYSFS_openRead("scenario/scn-order.fs");
	int scencount=0;
	if (fp)
	{
		rootNode=ReadDoc(fp);
		orderedScenarios = rootNode->getChild("fft-scnorder")->getChildren("scenario");
		if (!orderedScenarios.empty())
		{
			for (iter = orderedScenarios.begin(); iter != orderedScenarios.end(); iter++)
			{
				Scenario *Scen=new Scenario();
				std::string mapfn="scenario/";
				mapfn+=(*iter)->getString();
				Scen->ReadOnly(mapfn);
				scen[scencount]=mapfn;
				name[scencount]=Scen->GetName();
				desc[scencount]=Scen->GetDesc();
				module[scencount]=Scen->GetModuleName();
				scencount++;
				delete Scen;
			}
		}
		PHYSFS_close(fp);
	}

	//Find all remaining scenario files
	scnlist=PHYSFS_enumerateFiles("scenario");
	for (k = scnlist; *k != NULL; k++)
	{
		int check=0;
		bool goahead=true;
		if (!orderedScenarios.empty())
		{
			for (iter = orderedScenarios.begin(); iter != orderedScenarios.end(); iter++)
			{
				std::string compfn="scenario/";
				compfn+=(*iter)->getString();
				if (!strcmp(scen[check].c_str(),compfn.c_str())) goahead=false;
				check++;
			}
		}
		if(IsScenario(*k) && goahead)
		{
			Scenario *Scen=new Scenario();
			std::string mapfn="scenario/";
			mapfn+=*k;
			Scen->ReadOnly(mapfn);
			scen[scencount]=mapfn;
			name[scencount]=Scen->GetName();
			desc[scencount]=Scen->GetDesc();
			module[scencount]=Scen->GetModuleName();
			scencount++;
			delete Scen;
		}
	}
	if (!scencount) SCN_Invalid("List", "Could not find any scenarios");
	int cur=0;
	PHYSFS_freeList(scnlist);
	int getx, gety;
	int click=-1;
	while(!done)
	{
		Slock();
		while (SDL_PollEvent(&event))
		{
			// an event was found
			switch (event.type) {
			// close button clicked
			case SDL_QUIT:
				exit(0);
				break;

			// handle the keyboard
			case SDL_KEYDOWN:
				switch (event.key.keysym.sym) {
					case SDLK_ESCAPE:
					retval="";
					done = 1;
					break;
					default:
						break;
				}
				break;
			case SDL_MOUSEMOTION:
				SDL_GetMouseState(&getx, &gety);
				sGUI->SendMouseMotion(getx,gety);
				break;
			case SDL_MOUSEBUTTONDOWN:
				SDL_GetMouseState(&getx, &gety);
				click = sGUI->SendMouseClick(getx, gety);
				break;
			case SDL_MOUSEBUTTONUP:
				SDL_GetMouseState(&getx, &gety);
				if (click!=-1 && click==sGUI->SendMouseClick(getx, gety))
				{
					SDL_FillRect(screen,0,0);
					centerString(font14, w/2, 20, "Scenario Selection", white);
					centerString(font, w/2, 60, name[cur], white);
					drawString(font, 60, 80, "Description: ", white);
					drawString(font, 80, 100, desc[cur], white);
					sGUI->Draw();
					Sulock();
					SDL_Flip(screen);
					if (click==prev)
					{
						if (cur-1<0) cur=scencount-1;
						else cur--;
					}
					if (click==select)
					{
						retval=module[cur];
						done=1;
					}
					if (click==back)
					{
						retval="";
						done=1;
					}
					if (click==next)
					{
						if (cur+1>=scencount) cur=0;
						else cur++;
					}
				}
				sGUI->UpdateButtons();
				break;
			default:
				break;
			}
		}
		SDL_FillRect(screen,0,0);
		centerString(font14, w/2, 20, "Scenario Selection", white);
		centerString(font, w/2, 60, name[cur], white);
		drawString(font, 60, 80, "Description: ", white);
		drawString(font, 80, 100, desc[cur], white);
		sGUI->Draw();
		Sulock();
		SDL_Flip(screen);
	}
	TTF_CloseFont(font);
	TTF_CloseFont(font14);
	delete sGUI;
	delete rootNode;
	return retval;
}
void SCN_Invalid(std::string scn, std::string message)
{
	TTF_Font *font=TTF_OpenFont("fonts/arial.ttf", 12);
	SDL_Color white = { 0xFF, 0xFF, 0xFF, 0 };
	SDL_Surface *screen=SDL_GetVideoSurface();
	std::string msg[20];
	char c;
	Uint16 i=0;
	int end=0;
	int done=0;
	std::string msghead;
	c=message[i];
	while(!done) {
		if(c != 0x0A) {
			msg[end] += c;
		}
		else end++;
		i++;
		if (i>=message.size()) done=1;
		c=message[i];
	}
	msghead="Scenario: ";
	msghead+=scn;
	msghead+=" was invalid for the following reasons:";
	Uint32 ticks=SDL_GetTicks();
	SDL_Event event;
	bool logged=false;
	while (SDL_GetTicks()<ticks+30000)
	{
		while (SDL_PollEvent(&event))
		{
			// an event was found
			switch (event.type) {
			// close button clicked
			case SDL_QUIT:
				exit(1);
				break;
			}
		}
		SDL_FillRect(screen,0,0);
		drawString(font, screen->w/2-200, 20, msghead, white);
		if (!logged) Log::WriteVerbose(msghead);
		for (i=0; i<=end; i++)
		{
			drawString(font, screen->w/2-200, 40+(i*20), msg[i], white);
			if (!logged) Log::WriteVerbose(msg[i]);
		}
		drawString(font, screen->w/2-200, 40+((i+1)*20), "This game will autoclose in 30 seconds", white);
		SDL_Flip(screen);
		logged=true;
	}
	exit(1);
}
FPKShip **LoadShipsFromScen(Scenario *Scen)
{
	Log::WriteVerbose("Inside LoadShipsFromScen");
	char **fpklist;
	char **k;
	int i, j, temp, fpks, max;
	int total[60];
	static FPKShip *fpkships[100];
	for(i=0; i<100; i++)
	{
		fpkships[i]=0;
	}
	fpklist=PHYSFS_enumerateFiles("fpk");
	fpks=FPK_count();
	i=0;
	max=0;
	for (k = fpklist; *k != NULL; k++)
	{
		if(IsFPK(*k))
		{
			total[i]=FPK_countPlayerShips(*k);
			max+=total[i];
			i++;
		}
	}
	PHYSFS_freeList(fpklist);
	//make sure the ship that shows up first is the right one!
	temp=0;
	for(i=0; i<fpks; i++)
	{
		for(j=temp; j<total[i]+temp; j++)
		{
			FPKShip *tempship=new FPKShip(i, j-temp);
			if (Scen->ShipIsAllowed(tempship->GetName(),tempship->GetFPK()))
			{
				fpkships[j]=tempship;
			}
			else delete tempship;
		}
		temp=j;
	}
	return fpkships;
}

