// Level Handler.
// Worthless Bums 2012.


function saveCurrentLevel (%saveFile)
{//echo("saveCurrentLevel()");
	%mazeDimension = $mazeDimension;
	if ($generateNewLevel)
	{
		%saveFile.WriteLine("levelData");
		%saveFile.WriteLine("levelData" SPC %i SPC %j 	SPC
							"generate"					SPC		//  1) Status.
							-1							SPC		//  2) Layer.
							-1							SPC		//  3) Graph.
							-1							SPC		//  4) Position.	THIS WILL BE IN TWO PARTS!
							-1							SPC		//  5) Scenegraph.
							-1							SPC		//  6) Image.
							-1							SPC		//  7) Visible.
							-1							SPC		//  8) Size.		THIS WILL BE IN TWO PARTS!
							-1							SPC		//  9) xIndex.
							-1							SPC		// 10) yIndex.
							-1							SPC		// 11) Light.
							-1							SPC		// 12) Painting.
							-1							SPC		// 13) Wall Pipes.
							-1							SPC		// 14) Porthole.
							-1							SPC		// 15) Wall Pipe Object.
							-1							SPC		// 16) (Side) Wall Pipe Object.
							-1							SPC		// 17) Pump.
							-1);								// 18) Plastic Explosive.
	}
	else
	{
		%saveFile.WriteLine("levelData");
		// Loop through and write level data.
		for (%i = 0; %i < %mazeDimension; %i++)
		{
			for (%j = 0; %j < %mazeDimension; %j++)
			{	
				if (isObject($mazeRoom[%i, %j]))
				{//echo("--------> TILE DETECTED!");
					%paintingImage = isObject($mazeRoom[%i, %j].painting) ? ($mazeRoom[%i, %j].painting).image : "null";
					%lightSourceVisible = 0;
					if (isObject(($mazeRoom[%i, %j].light).lightSource))
					{
						%lightSourceVisible = (($mazeRoom[%i, %j].light).lightSource).visible;
					}
					%pipesImag = null;
					if (isObject(($mazeRoom[%i, %j].pipes)))
					{
						%pipesImag = ($mazeRoom[%i, %j].pipes).image;
					}
					%saveFile.WriteLine("levelData" SPC %i SPC %j 						SPC
										$mazeRoom[%i, %j].status						SPC		//  1) Status.
										$mazeRoom[%i, %j].SceneLayer					SPC		//  2) Layer.
										"-1"											SPC		//  3) Graph.
										$mazeRoom[%i, %j].position						SPC		//  4) Position.	THIS WILL BE IN TWO PARTS!
										"-1"											SPC		//  5) Scenegraph.
										$mazeRoom[%i, %j].image							SPC		//  6) Image.
										$mazeRoom[%i, %j].frame							SPC		//  7) Frame.
										$mazeRoom[%i, %j].visible						SPC		//  8) Visible.
										$mazeRoom[%i, %j].size							SPC		//  9) Size.		THIS WILL BE IN TWO PARTS!
										$mazeRoom[%i, %j].xIndex						SPC		// 10) xIndex.
										$mazeRoom[%i, %j].yIndex						SPC		// 11) yIndex.
										isObject($mazeRoom[%i, %j].light)				SPC		// 12) Light.
										%lightSourceVisible								SPC		// 13) Light source visible.
										%paintingImage									SPC		// 14) Painting.
										$mazeRoom[%i, %j].frame							SPC		// 15) Frame.
										%pipesImage										SPC		// 16) Pipes. Should be paintings?
										isObject($mazeRoom[%i, %j].porthole)			SPC		// 17) Porthole.
										isObject($mazeRoom[%i, %j].wallPipeObject)		SPC		// 18) Wall Pipe Object.
										isObject($mazeRoom[%i, %j].sideWallPipe)		SPC		// 19) Wall Pipe Object.
										isObject($mazeRoom[%i, %j].plasticExplosive)	SPC		// 20) Plastic Explosive.
										isObject($mazeRoom[%i, %j].pump));						// 21) Pump.
				}
				else
				{
					if ($mazeRoom[%i, %j] == -12)	// Non-adjacent space tile!
					{//echo("WRITING NON-ADJACENT SPACE TILE!");
						%saveFile.WriteLine("levelData" SPC %i SPC %j SPC "SPACETILE");
					}
					else
					{
						%saveFile.WriteLine("levelData" SPC %i SPC %j SPC "EOL");
					}
				}
			}
		}
	}
}
function loadCurrentLevel (%saveFile)	// NOTE: This code was ripped from generateSpecifiedIrregularDungeon() so fix that first then copy here!
{//echo("loadCurrentLevel()");
	destroyMazeRoom();
	if (isObject($PreloadedTilemap))
	{
		$PreloadedTilemap.safeDelete();
	}
	$PreloadedTilemap = new Sprite();
	$PreloadedTilemap.Image = "Sprites:PreloadedCommandDeck";
	%preloadedPosition = 64 SPC (64 + $GlobalVerticalShift);
	$PreloadedTilemap.position = %preloadedPosition;
	$PreloadedTilemap.size = "128 128";
	$PreloadedTilemap.SceneLayer = $PreloadedTilemapLayer;
	addObjectToScene($PreloadedTilemap);
	%mazeDimension = $mazeDimension;
	$mazeRoom[%mazeDimension, %mazeDimension] = 0;
	// Find the level data.
	for (%line = %saveFile.ReadLine(); !(%line $= ""); %line = %saveFile.ReadLine())
	{
		%word = GetWord(%line, 0);
		if (%word $= "levelData")
		{
			break;
		}
	}
	// Loop through and fill data.
	for (%i = 0; %i < %mazeDimension; %i++)
	{
		for (%j = 0; %j < %mazeDimension; %j++)
		{
			%line = %saveFile.ReadLine();
			// This really should be outside the loop...
			if (getWord(%line, 3) $= "generate")
			{
				generateRandomLevel();
				return;
			}
			// We're looking for up to twenty-one (21) words of data per line.
			// NOTE: No checks yet to determine corrupt/altered save file!
			%levelDataLabel = getWord(%line, 0);
			%x = getWord(%line, 1);
			%y = getWord(%line, 2);
			%status = getWord(%line, 3);
			%SceneLayer = getWord(%line, 4);
			%graph = getWord(%line, 5);
			%position = getWord(%line, 6) SPC getWord(%line, 7);
			%scenegraph = getWord(%line, 8);
			%image = getWord(%line, 9);
			%frame = getWord(%line, 10);
			%visible = getWord(%line, 11);
			%size = getWord(%line, 12) SPC getWord(%line, 13);
			%xIndex = getWord(%line, 14);
			%yIndex = getWord(%line, 15);
			%light = getWord(%line, 16);
			%lightVisible = getWord(%line, 17);
			%painting = getWord(%line, 18);
			%frame = getWord(%line, 19);
			%pipes = getWord(%line, 20);
			%porthole = getWord(%line, 21);
			%wallPipeObject = getWord(%line, 22);
			%sideWallPipe = getWord(%line, 23);
			%plasticExplosive = getWord(%line, 24);
			%pump = getWord(%line, 25);
			
			// Check the status word.
			if (%status $= "SPACETILE")	// Non-adjacent space tile!
			{//echo("LOADING NON-ADJACENT SPACE TILE!");
				$mazeRoom[%x, %y] = -12;
			}
			else if (%status $= "EOL"	||
					 %image $= "")
			{
				// This is not a static sprite tile. We can ignore it.
				// We may need this code block later when adding new tile/wall elements!
			}
			else
			{//echo("%image =" SPC %image);
				// Create tile.
				$mazeRoom[%x, %y] = new Sprite("tile")		// Do we care about tile names? Probably not...
				{
					status = %status;
					SceneLayer = %SceneLayer;
					graph = %graph;
					position = %position;
					scenegraph = levelSceneGraph;//%scenegraph;		// HACK! Beware future custom map generation/loading!
					image = %image;
					frame = %frame;
					visible = %visible;
					size = %size;
					xIndex = %xIndex;
					yIndex = %yIndex;
					light = %light;
					painting = %painting;
					frame = %frame;
					pipes = %pipes;
					porthole = %porthole;
					wallPipeObject = %wallPipeObject;
					pump = %pump;
				};
				addObjectToScene($mazeRoom[%x, %y]);
				
				// Handle elevator tile.
				//if (%image $= getElevatorSprite())		// $overworldLocation isn't set yet!
				if (strstr(%image, "Elevator") >= 0)
				{//echo("1");
					$stairsXIndex = %x;
					$stairsYIndex = %y;
					$stairsPositionX = getWord(%position, 0);
					$stairsPositionY = getWord(%position, 1);
				}
				
				// Add lights here.
				if ($mazeRoom[%x, %y].light)
				{
					// Get the appropriate light for its associated wall tile.
					%lightImage = getLightImageFromAtlasFrame($mazeRoom[%x, %y].frame);
					// Make sure this tile is a wall.
					if (%lightImage !$= "")
					{
						// Handle offsets here.
						%xOffset = 0;
						%yOffset = 0;
						switch$ (%lightImage)
						{
							case "Sprites:LightFloorLeft":		%xOffset = -5.6;
							case "Sprites:LightFloorRight":		%xOffset =  5.6;
						}
						
						// Create light sprite.
						%light = new Sprite("Light")
						{
							SceneLayer = 25;
							graph = 26;
							position = getTileShiftedPositionFromIndices(%x, %y);
							scenegraph = levelSceneGraph;
							image = %lightImage;
							visible = true;
							size = "4 4";
							lightSource = null;
							xIndex = %x;
							yIndex = %y;
						};
						addObjectToScene(%light);
						%lightSource = createWallLightSource();
						%lightSource.setVisible(%lightVisible);
						$LightSourceList.add(%lightSource);
						if (%xOffset > 0)
						{
							%lightSource.setFlipX(1);
						}
						$mazeRoom[%x, %y].light = %light;
						%light.lightSource = %lightSource;
						$lightList.add(%light);
						
						/*
						// Find proper light to mount to this light.
						switch$ (%lightImage)
						{
							case "LightFloorLeftImageMap":
								%lightMountLight = LightWallLeftImageMap;
								%xOffset = 0;
							case "LightFloorRightImageMap":
								%lightMountLight = LightWallRightImageMap;
								%xOffset = 0;
						}
						// Attach "wall" light next to this light.
						%lightMount = new Sprite("Light Mount")
						{
							SceneLayer = 25;
							graph = 26;
							position = getTileShiftedPositionFromIndices(%x, %y);
							scenegraph = levelSceneGraph;
							image = %lightMountLight;
							visible = true;
							size = "4 4";
						};
						addObjectToScene(%lightMount);
						// Mount light to light mount.
						// NOTE: Offset mount depending on type of light fixture!
						%lightMount.mount($mazeRoom[%x, %y], %xOffset, %yOffset, 50.0, true, true, true, true);
						*/
					}
				}
				// Create painting if necessary.
				if (%painting !$= ""	&&
					%painting !$= "null")
				{//echo("%painting =" SPC %painting);
					// Create painting sprite.
					%wallPainting = new Sprite("Painting")
					{
						SceneLayer = $PaintingLayer;
						position = getTileShiftedPositionFromIndices(%x, %y);
						image = %painting;
						visible = true;
						size = "4 4";
					};
					addObjectToScene(%wallPainting);
					$mazeRoom[%x, %y].painting = %wallPainting;
				}
				// Attach wall pipes if required.
				if (%pipes $= "PaintingHorizontal1ImageMap"	||
					%pipes $= "PaintingHorizontal2ImageMap")
				{//echo("LOADING PIPES ON " SPC %x SPC %y);
					// Create wall pipes sprite.
					%wallPipes = new Sprite("Wall Pipes")
					{
						SceneLayer = $WallPipesLayer;
						graph = $WallPipesGraph26;
						position = getTileShiftedPositionFromIndices(%x, %y);
						scenegraph = levelSceneGraph;
						image = %pipe;
						visible = true;
						size = "4 4";
					};
					addObjectToScene(%wallPipes);
					// Set pipe offsets.
					%xOffset = -1.8;
					%yOffset = 0;
					// Assign pipes to wall.
					$mazeRoom[%x, %y].pipes = %wallPipes;
					// Mount pipes to wall.
					%wallPipes.mount($mazeRoom[%x, %y], %xOffset, %yOffset, 50.0, true, true, true, true);
				}
				if (%porthole)
				{
					createPorthole(%x, %y);
				}
				if (%wallPipeObject)
				{
					createWallPipes(%x, %y);
				}
				if (%sideWallPipe == 1)
				{
					createRightSideWallPipes(%x, %y);
				}
				if (%sideWallPipe == 2)
				{
					createLeftSideWallPipes(%x, %y);
				}
				//echo("%plasticExplosive =" SPC %plasticExplosive);
				if (%plasticExplosive)
				{
					createPlasticExplosiveAnimation(%x, %y);
				}
				if (%pump)
				{
					createPumpAnimation(%x, %y);
				}
			}
			//echo("tile" SPC %i SPC %j SPC "created!");
		}
	}
}

// Saves the current lifted level to the save file.
function saveCurrentLiftedLevel (%saveFile)
{//echo("saveCurrentLiftedLevel()");
	%mazeDimension = $mazeDimension;//32;
	// Check whether to generate a new level or save the current one.
	if ($generateNewLevel)
	{
		%saveFile.WriteLine("liftedLevelData 0");
	}
	else
	{
		%saveFile.WriteLine("liftedLevelData 1");
		// Loop through and write lifted level data.
		for (%i = 0; %i < %mazeDimension; %i++)
		{
			for (%j = 0; %j < %mazeDimension; %j++)
			{	
				if (isObject($mazeLiftedTiles[%i, %j]))
				{
					// Save the tile line.
					%saveFile.WriteLine("liftedLevelData" SPC 1 SPC %i SPC %j);
				}
				else
				{
					// Save the (empty!) tile line.
					//%saveFile.WriteLine("liftedLevelData" SPC 0);
				}
			}
		}

		// Don't close the file handle - that is the responsibility of the caller, function saveCurrentGame()!
	}
}

// Loads the current lifted level from save file.
function loadCurrentLiftedLevel (%saveFile)
{//echo("loadCurrentLiftedLevel()");
	// Clear $mazeLiftedTiles.
	destroyMazeLiftedTiles();
	// Find the lifted level data.
	for (%line = %saveFile.ReadLine(); !(%line $= ""); %line = %saveFile.ReadLine())
	{
		%word = GetWord(%line, 0);
		if (%word $= "liftedLevelData")
		{//echo("liftedLevelData found!");
			break;
		}
	}
	
	// Loop through and fill data.
	for (%line = %saveFile.ReadLine(); !(%line $= ""); %line = %saveFile.ReadLine())
	{
		// Get a line.
		%line = %saveFile.ReadLine();
		
		// We're looking for up to four (4) words of data per line.
		// NOTE: No checks yet to determine corrupt/altered save file!
		%liftedLevelDataLabel = getWord(%line, 0);
		if (%liftedLevelDataLabel $= "liftedLevelData")
		{
			%validLiftedLevelTile = getWord(%line, 1);
			if (%validLiftedLevelTile)
			{//echo("%validLiftedLevelTile =" SPC %validLiftedLevelTile);
				%xIndex = getWord(%line, 2);
				%yIndex = getWord(%line, 3);
				spawnLiftedFloorTile(%xIndex, %yIndex);		// Memory leak!
			}
		}
	}
}

// Saves current monster data to save file.
function saveCurrentMonsterData (%saveFile)
{//echo("saveCurrentMonsterData()");
	// Write the total number of monsters we have.
	%totalMonsters = $monsterList.getCount();
	%saveFile.WriteLine("monsterDataTotal" SPC %totalMonsters SPC $maxMonsters);		// Need $maxMonsters for calculating Hostile Control on decks!
	
	// Loop through and write monster data.
	for (%i = 0; %i < %totalMonsters; %i++)
	{
		// Grab the monster.
		%monster = $monsterList.getObject(%i);
		
		// We save thirty-three (33) pieces of monster data:
		// Save the monster line.
		%saveFile.WriteLine(%monster.name					SPC		//  1) Name.
							%monster.level					SPC		//  2) Level.
							%monster.SceneLayer				SPC		//  3) Layer.
							%monster.graph					SPC		//  4) Graph.
							%monster.scenegraph				SPC		//  5) Scenegraph.
							%monster.Animation				SPC		//  6) Animation Name.
							%monster.position				SPC		//  7) Position.	THIS WILL BE IN TWO PARTS!
							%monster.size					SPC		//  8) Size.		THIS WILL BE IN TWO PARTS!
							%monster.visible				SPC		//  9) Visible.
							%monster.xIndex					SPC		// 10) xIndex.
							%monster.yIndex					SPC		// 11) yIndex.
							%monster.facing					SPC		// 12) Facing.
							%monster.currentHealth			SPC		// 13) Current Health.
							%monster.maxHealth				SPC		// 14) Max Health.
							%monster.currentActionPoints	SPC		// 15) Current AP.
							%monster.maximumActionPoints	SPC		// 16) Max AP.
							%monster.armorRating			SPC		// 17) Armor Rating.
							%monster.baseDamage				SPC		// 18) Base Damage.
							%monster.attackModifier			SPC		// 19) Attack Modifier.
							%monster.evasion				SPC		// 20) Evasion.
							%monster.canBurrow				SPC		// 21) Can Burrow.
							%monster.burrow					SPC		// 22) Burrowed.
							%monster.canRange				SPC		// 23) Can Range.
							%monster.defensiveCaster		SPC		// 24) Defensive Caster.
							%monster.range					SPC		// 25) Range.
							%monster.hasBeenSpotted			SPC		// 26) Has Been Spotted.
							%monster.isActive				SPC		// 27) Has Been Spotted.
							%monster.meleeDamageType		SPC		// 28) Melee Damage Type.
							%monster.rangeDamageType		SPC		// 29) Range Damage Type.
							%monster.baseMeleeDamage		SPC		// 30) Base Melee Damage.
							%monster.baseRangeDamage		SPC		// 31) Base Range Damage.
							%monster.isHuman				SPC		// 32) Is a human.
							%monster.isRobot				SPC		// 33) Is a robot.
							%monster.isAlien				SPC		// 34) Is an alien.
							%monster.stasis							// 35) Stasis.
							);
	}
	
	// Don't close the file handle - that is the responsibility of the caller, function saveCurrentGame()!
}

// Loads the monster data from save file.
function loadCurrentMonsterData ()
{//echo("loadCurrentMonsterData()");
	// Check load flag!
	if ($generateNewLevelFromLoad)
	{
		// Spawn monsters since the level is already loaded.
		%numberOfMonsters = getDungeonLevelSpawnCount();
		spawnMonsters(%numberOfMonsters);
		return;
	}
	// Sets the file to directory path: "C:\Users\<user>\AppData\Roaming\Steam Marines\"
	%filePath = getSaveGameFilePath();
	%saveFile = new fileobject();
	%ret = %saveFile.OpenForRead(%filePath);
	if (!%ret)
	{//echo("Bad save file!");
		error("Invalid save file!");
		return false;
	}
	$monsterList = new SimSet();
	for (%line = %saveFile.ReadLine(); !(%line $= ""); %line = %saveFile.ReadLine())
	{
		%word = GetWord(%line, 0);
		if (%word $= "monsterDataTotal")
		{
			%totalMonsters = getWord(%line, 1);
			$maxMonsters = getWord(%line, 2);		// Need this for calculating Hostile Control on decks!
			break;
		}
	}
	for (%i = 0; %i < %totalMonsters; %i++)
	{
		%line = %saveFile.ReadLine();
		// We're looking for thirty-five (35) words of data per line.
		// NOTE: No checks yet to determine corrupt/altered save file!
		%name = getWord(%line, 0);
		%level = getWord(%line, 1);
		%SceneLayer = getWord(%line, 2);
		%graph = getWord(%line, 3);
		%scenegraph = getWord(%line, 4);
		%Animation = getWord(%line, 5);
		%position = getWord(%line, 6) SPC getWord(%line, 7);
		%size = getWord(%line, 8) SPC getWord(%line, 9);
		%visible = getWord(%line, 10);
		%xIndex = getWord(%line, 11);
		%yIndex = getWord(%line, 12);
		%facing = getWord(%line, 13);
		%currentHealth = getWord(%line, 14);
		%maxHealth = getWord(%line, 15);
		%currentActionPoints = getWord(%line, 16);
		%maximumActionPoints = getWord(%line, 17);
		%armorRating = getWord(%line, 18);
		%baseDamage = getWord(%line, 19);
		%attackModifier = getWord(%line, 20);
		%evasion = getWord(%line, 21);
		%canBurrow = getWord(%line, 22);
		%burrow = getWord(%line, 23);
		%canRange = getWord(%line, 24);
		%defensiveCaster = getWord(%line, 25);
		%range = getWord(%line, 26);
		%hasBeenSpotted = getWord(%line, 27);
		%isActive = getWord(%line, 28);
		%meleeDamageType = getWord(%line, 29);
		%rangeDamageType = getWord(%line, 30);
		%baseMeleeDamage = getWord(%line, 31);
		%baseRangeDamage = getWord(%line, 32);
		%isHuman = getWord(%line, 33);
		%isRobot = getWord(%line, 34);
		%isAlien = getWord(%line, 35);
		%stasis = getWord(%line, 36);
		// Create monster.
		%monster = new Sprite("" @ %name)
		{
			name = %name;
			level = %level;
			SceneLayer = %SceneLayer;
			graph = %graph;
			scenegraph = levelSceneGraph;	// Beware future level customization!
			Animation = %Animation;
			position = %position;
			size = %size;
			visible = %visible;
			xIndex = %xIndex;
			yIndex = %yIndex;
			facing = %facing;
			currentHealth = %currentHealth;
			maxHealth = %maxHealth;
			currentActionPoints = %currentActionPoints;
			maximumActionPoints = %maximumActionPoints;
			armorRating = %armorRating;
			baseDamage = %baseDamage;
			attackModifier = %attackModifier;
			evasion = %evasion;
			canBurrow = %canBurrow;
			burrow = %burrow;
			canRange = %canRange;
			defensiveCaster = %defensiveCaster;
			range = %range;		// In Torque internal units - tiles are 4x4.
			hasBeenSpotted = %hasBeenSpotted;
			isActive = %isActive;
			meleeDamageType = %meleeDamageType;
			rangeDamageType = %rangeDamageType;
			baseMeleeDamage = %baseMeleeDamage;
			baseRangeDamage = %baseRangeDamage;
			isHuman = %isHuman;
			isRobot = %isRobot;
			isAlien = %isAlien;
			
			// NOT PERSISTED IN SAVE FILE.
			weapon = null;
			healthIndicator = null;
			sleepAnimation = null;
			onFireEffect = null;
			chargeAnimation = null;
			// END NOT PERSISTED IN SAVE FILE.
			
			stasis = %stasis;
		};
		addObjectToScene(%monster);
		%monster.originalSize = %monster.size;
		$monsterList.add(%monster);
		if (%stasis)
		{
			createStasisAnimation(%monster);
		}
	}
	// Don't close the file handle - that is the responsibility of the caller, function saveCurrentGame()!
}
function saveCurrentItemData (%saveFile)
{//echo("saveCurrentItemData()");
	%totalMapItems = $mapItems.getCount();
	%saveFile.WriteLine("itemData" SPC %totalMapItems);
	for (%i = 0; %i < %totalMapItems; %i++)
	{
		%item = $mapItems.getObject(%i);
		%saveFile.WriteLine("itemData" 			SPC
							%item.name			SPC
							%item.SceneLayer	SPC
							%item.scenegraph	SPC
							%item.itemType		SPC
							%item.value			SPC
							%item.image			SPC
							%item.position		SPC
							%item.equipSlot		SPC
							%item.canBeUsed		SPC
							%item.size			SPC
							%item.xIndex		SPC
							%item.yIndex		SPC
							%item.visible		SPC
							getItemCode(%item, %i));
	}
	// Don't close the file handle - that is the responsibility of the caller, function saveCurrentGame()!
}
function loadCurrentItemData ()
{//echo("loadCurrentItemData()");
	// Check load flag!
	if ($generateNewLevelFromLoad)
	{
		return;
	}
	// Sets the file to directory path: "C:\Users\<user>\AppData\Roaming\Steam Marines\"
	%filePath = getSaveGameFilePath();
	%saveFile = new fileobject();
	%ret = %saveFile.OpenForRead(%filePath);
	if (!%ret)
	{//echo("Bad save file!");
		error("Invalid save file!");
		return false;
	}
	%totalItems = 0;
	for (%line = %saveFile.ReadLine(); !(%line $= ""); %line = %saveFile.ReadLine())
	{
		%word = getWord(%line, 0);
		if (%word $= "itemData")
		{
			%totalItems = getWord(%line, 1);
			break;
		}
	}
	if (%totalItems <= 0)
	{
		return;
	}
	for (%i = 0; %i < %totalItems; %i++)
	{
		%line = %saveFile.ReadLine();
		// We're looking for fourteen (14) words of data per line.
		// NOTE: No checks yet to determine corrupt/altered save file!
		%name = getWord(%line, 1);
		%SceneLayer = getWord(%line, 2);
		%scenegraph = getWord(%line, 3);
		%itemType = getWord(%line, 4);
		%value = getWord(%line, 5);
		%image = getWord(%line, 6);
		%position = getWord(%line, 7) SPC getWord(%line, 8);
		%equipSlot = getWord(%line, 9);
		%canBeUsed = getWord(%line, 10);
		%size = getWord(%line, 11) SPC getWord(%line, 12);
		%xIndex = getWord(%line, 13);
		%yIndex = getWord(%line, 14);
		%visible = getWord(%line, 15);
		%itemCode = getWord(%line, 16);
		%item = getItemFromSaveFile(%itemType, %position, %xIndex, %yIndex);
		$mapItems.add(%item);
	}
	// Don't close the file handle - that is the responsibility of the caller, function saveCurrentGame()!
}

// Saves current fog of war data to save file.
function saveCurrentFogOfWarData (%saveFile)
{//echo("saveCurrentFogOfWarData()");
	// Write the fog of war data.
	%saveFile.WriteLine("fogOfWarData");
	for (%x = 0; %x < $fogOfWar.getTileCountX(); %x++)
	{
		for (%y = 0; %y < $fogOfWar.getTileCountY(); %y++)
		{
			// Grab the fog of war tile image.
			%tileImage = getWord($fogOfWar.getTileType(%x, %y), 1);
			%saveFile.WriteLine("fogOfWarData" SPC %x SPC %y SPC %tileImage);
		}
	}
}

// Loads the monster data from save file.
function loadCurrentFogOfWarData ()
{//echo("loadCurrentFogOfWarData()");
	// Check load flag!
	if ($generateNewLevelFromLoad)
	{
		return;
	}
	
	// Sets the file to directory path: "C:\Users\<user>\AppData\Roaming\Steam Marines\"
	%filePath = getSaveGameFilePath();
	// The save file object.
	%saveFile = new fileobject();
	// Check the file open status.
	%ret = %saveFile.OpenForRead(%filePath);
	// Can't open the file.
	if (!%ret)
	{//echo("Bad save file!");
		error("Invalid save file!");
		return false;
	}
	
	// Find the fog of war data.
	for (%line = %saveFile.ReadLine(); !(%line $= ""); %line = %saveFile.ReadLine())
	{
		%word = GetWord(%line, 0);
		if (%word $= "fogOfWarData")
		{
			break;
		}
	}
	
	// Loop through and fill data.
	for (%x = 0; %x < $mazeDimension + 1; %x++)
	{
		for (%y = 0; %y < $mazeDimension + 1; %y++)
		{
			// Get a line.
			%line = %saveFile.ReadLine();
			// We're looking for four (4) words of data per line.
			// NOTE: No checks yet to determine corrupt/altered save file!
			%name = getWord(%line, 0);
			%xIndex = getWord(%line, 1);
			%yIndex = getWord(%line, 2);
			%tileImage = getWord(%line, 3);
			
			// Set fog of war tile.
			$fogOfWar.setStaticTile(%x, %y, %tileImage, 0);
		}
	}
	
	// Don't close the file handle - that is the responsibility of the caller, function saveCurrentGame()!
}

// Saves current barrel data to save file.
function saveCurrentBarrelData (%saveFile)
{//echo("saveCurrentBarrelData()");
	// Write the barrel data.
	%barrelCount = $barrelList.getCount();
	%saveFile.WriteLine("barrelData" SPC %barrelCount);
	for (%i = 0; %i < %barrelCount; %i++)
	{
		// Grab the barrel.
		%barrel = $barrelList.getObject(%i);
		
		// We save nine (9) pieces of data.
		%saveFile.WriteLine("barrelData"		SPC
							%barrel.SceneLayer	SPC
							%barrel.graph		SPC
							%barrel.position	SPC
							%barrel.scenegraph	SPC
							%barrel.image		SPC
							%barrel.visible		SPC
							%barrel.size		SPC
							%barrel.xIndex		SPC
							%barrel.yIndex);
	}
}

// Loads the barrel data from save file.
function loadCurrentBarrelData ()
{//echo("loadCurrentBarrelData()");
	// Check load flag!
	if ($generateNewLevelFromLoad)
	{
		
		return;
	}
	
	// Sets the file to directory path: "C:\Users\<user>\AppData\Roaming\Steam Marines\"
	%filePath = getSaveGameFilePath();
	// The save file object.
	%saveFile = new fileobject();
	// Check the file open status.
	%ret = %saveFile.OpenForRead(%filePath);
	// Can't open the file.
	if (!%ret)
	{//echo("Bad save file!");
		error("Invalid save file!");
		return false;
	}
	
	// Find the barrel data.
	%totalBarrels = 0;
	for (%line = %saveFile.ReadLine(); !(%line $= ""); %line = %saveFile.ReadLine())
	{
		%word = getWord(%line, 0);
		if (%word $= "barrelData")
		{
			%totalBarrels = getWord(%line, 1);
			break;
		}
	}
	
	// Loop through and fill data.
	for (%i = 0; %i < %totalBarrels; %i++)
	{
		// Get next line.
		%line = %saveFile.ReadLine();
		
		// Grab data.
		%SceneLayer = getWord(%line, 1);
		%graph = getWord(%line, 2);
		%position = getWord(%line, 3) SPC getWord(%line, 4);
		%scenegraph = getWord(%line, 5);
		%image = getWord(%line, 6);
		%visible = getWord(%line, 7);
		%size = getWord(%line, 8) SPC getWord(%line, 9);
		%xIndex = getWord(%line, 10);
		%yIndex = getWord(%line, 11);
		
		// Create barrel sprite.
		%barrelSprite = new Sprite("Barrel")
		{
			SceneLayer = %SceneLayer;
			graph = %graph;
			position = %position;
			scenegraph = levelSceneGraph;
			image = %image;
			visible = %visible;
			size = %size;
			xIndex = %xIndex;
			yIndex = %yIndex;
		};
		addObjectToScene(%barrelSprite);

		// Add barrel to list of barrels.
		$barrelList.add(%barrelSprite);
	}
	
	// Don't close the file handle - that is the responsibility of the caller, function saveCurrentGame()!
}

// Saves current console data to save file.
function saveCurrentConsoleData (%saveFile)
{//echo("saveCurrentConsoleData()");
	// Write the console data.
	%consoleCount = $consoleList.getCount();
	%saveFile.WriteLine("consoleData" SPC %consoleCount);
	for (%i = 0; %i < %consoleCount; %i++)
	{
		// Grab the console.
		%console = $consoleList.getObject(%i);
		
		// We save twelve (12) pieces of data.
		%saveFile.WriteLine("consoleData"			SPC
							%console.SceneLayer		SPC
							%console.graph			SPC
							%console.position		SPC
							%console.scenegraph		SPC
							%console.image			SPC
							%console.visible		SPC
							%console.size			SPC
							%console.xIndex			SPC
							%console.yIndex			SPC
							%console.poweredOn		SPC
							%console.destructible	SPC
							%console.broken			SPC
							%console.dialogueID);
	}
}

// Loads the console data from save file.
function loadCurrentConsoleData ()
{//echo("loadCurrentConsoleData()");
	// Check load flag!
	if ($generateNewLevelFromLoad)
	{
		
		return;
	}
	
	// Sets the file to directory path: "C:\Users\<user>\AppData\Roaming\Steam Marines\"
	%filePath = getSaveGameFilePath();
	// The save file object.
	%saveFile = new fileobject();
	// Check the file open status.
	%ret = %saveFile.OpenForRead(%filePath);
	// Can't open the file.
	if (!%ret)
	{//echo("Bad save file!");
		error("Invalid save file!");
		return false;
	}
	
	// Find the console data.
	%totalConsoles = 0;
	for (%line = %saveFile.ReadLine(); !(%line $= ""); %line = %saveFile.ReadLine())
	{
		%word = getWord(%line, 0);
		if (%word $= "consoleData")
		{
			%totalConsoles = getWord(%line, 1);
			break;
		}
	}
	
	// Loop through and fill data.
	for (%i = 0; %i < %totalConsoles; %i++)
	{
		// Get next line.
		%line = %saveFile.ReadLine();
		
		// Grab data.
		%SceneLayer = getWord(%line, 1);
		%graph = getWord(%line, 2);
		%position = getWord(%line, 3) SPC getWord(%line, 4);
		%scenegraph = getWord(%line, 5);
		%image = getWord(%line, 6);
		%visible = getWord(%line, 7);
		%size = getWord(%line, 8) SPC getWord(%line, 9);
		%xIndex = getWord(%line, 10);
		%yIndex = getWord(%line, 11);
		%poweredOn = getWord(%line, 12);
		%destructible = getWord(%line, 13);
		%broken = getWord(%line, 14);
		%dialogueID = getWord(%line, 15);
		
		// Spawn console.
		%console = new Sprite("console")
		{
			SceneLayer = %SceneLayer;
			graph = %graph;
			position = %position;
			scenegraph = levelSceneGraph;
			image = %image;
			visible = %visible;
			size = %size;
			xIndex = %xIndex;
			yIndex = %yIndex;
			poweredOn = %poweredOn;				// By default spawn consoles powered off.
			destructible = %destructible;		// Flag if this console is destructible or not; game critical consoles should not be destructible!
			broken = %broken;					// By default consoles are not broken.
			dialogueID = %dialogueID;
			dialogue = getConsoleDialogue(%console.dialogueID);
		};
		addObjectToScene(%console);
		
		// Add console to list.
		$consoleList.add(%console);
	}
	
	// Don't close the file handle - that is the responsibility of the caller, function saveCurrentGame()!
}

// Saves current dispenser data to save file.
function saveCurrentDispenserData (%saveFile)
{//echo("saveCurrentDispenserData()");
	// Write the dispenser data.
	%dispenserCount = $dispenserList.getCount();
	%saveFile.WriteLine("dispenserData" SPC %dispenserCount);
	for (%i = 0; %i < %dispenserCount; %i++)
	{
		// Grab the dispenser.
		%dispenser = $dispenserList.getObject(%i);
		
		// We save thirteen (13) pieces of data.
		%saveFile.WriteLine("dispenserData"				SPC
							%dispenser.SceneLayer		SPC
							%dispenser.graph			SPC
							%dispenser.position			SPC
							%dispenser.scenegraph		SPC
							%dispenser.image			SPC
							%dispenser.visible			SPC
							%dispenser.size				SPC
							%dispenser.xIndex			SPC
							%dispenser.yIndex			SPC
							%dispenser.poweredOn		SPC
							%dispenser.destructible		SPC
							%dispenser.broken			SPC
							%dispenser.lightOverlay);
	}
}

// Loads the dispenser data from save file.
function loadCurrentDispenserData ()
{//echo("loadCurrentDispenserData()");
	// Check load flag!
	if ($generateNewLevelFromLoad)
	{
		
		return;
	}
	
	// Sets the file to directory path: "C:\Users\<user>\AppData\Roaming\Steam Marines\"
	%filePath = getSaveGameFilePath();
	// The save file object.
	%saveFile = new fileobject();
	// Check the file open status.
	%ret = %saveFile.OpenForRead(%filePath);
	// Can't open the file.
	if (!%ret)
	{//echo("Bad save file!");
		error("Invalid save file!");
		return false;
	}
	
	// Find the dispenser data.
	%totalDispensers = 0;
	for (%line = %saveFile.ReadLine(); !(%line $= ""); %line = %saveFile.ReadLine())
	{
		%word = getWord(%line, 0);
		if (%word $= "dispenserData")
		{
			%totalDispensers = getWord(%line, 1);
			break;
		}
	}
	
	// Loop through and fill data.
	for (%i = 0; %i < %totalDispensers; %i++)
	{
		// Get next line.
		%line = %saveFile.ReadLine();
		
		// Grab data.
		%SceneLayer = getWord(%line, 1);
		%graph = getWord(%line, 2);
		%position = getWord(%line, 3) SPC getWord(%line, 4);
		%scenegraph = getWord(%line, 5);
		%image = getWord(%line, 6);
		%visible = getWord(%line, 7);
		%size = getWord(%line, 8) SPC getWord(%line, 9);
		%xIndex = getWord(%line, 10);
		%yIndex = getWord(%line, 11);
		%poweredOn = getWord(%line, 12);
		%destructible = getWord(%line, 13);
		%broken = getWord(%line, 14);
		%lightOverlay = getWord(%line, 15);
		
		// Spawn dispenser.
		%dispenser = new Sprite("dispenser")
		{
			SceneLayer = %SceneLayer;
			graph = %graph;
			position = %position;
			scenegraph = levelSceneGraph;
			image = %image;
			visible = %visible;
			size = %size;
			xIndex = %xIndex;
			yIndex = %yIndex;
			poweredOn = %poweredOn;				// By default spawn dispensers powered off.
			destructible = %destructible;		// Flag if this dispenser is destructible or not; game critical dispensers should not be destructible!
			broken = %broken;					// By default dispensers are not broken.
			lightOverlay = %lightOverlay;		// Powered off means no light overlay mounted.
		};
		addObjectToScene(%dispenser);
		
		// Add dispenser to list.
		$dispenserList.add(%dispenser);
		
		// Dispenser light overlay!
		if (%dispenser.lightOverlay !$= "null")
		{
			// Dispenser is off.
			if (%dispenser.image $= getBigDispenserOffSprites()	||
				%dispenser.image $= getSmallDispenserOffSprites())
			{
				%dispenser.lightOverlay = null;
			}
			else
			{
				// Attach light overlay!
				%dispenserLight = new Sprite("dispenser light")
				{
					SceneLayer = %SceneLayer;
					graph = 2;
					position = getWord(%dispenser.getPosition(), 0) SPC getWord(%dispenser.getPosition(), 1) + 0.75;
					scenegraph = levelSceneGraph;
					image = "Sprites:ConsoleDispenserTileLight";
					visible = true;
					size = "5.5 7.125";
					xIndex = %dispenser.xIndex;
					yIndex = %dispenser.yIndex;
				};
				addObjectToScene(%dispenserLight);
				// Mount light overlay to dispenser.
				//%dispenserLight.mount(%dispenser, 0.0, 0.75, 50.0, true, true, true, true);
				%dispenser.lightOverlay = %dispenserLight;
			}
		}
	}
	
	// Don't close the file handle - that is the responsibility of the caller, function saveCurrentGame()!
}

// Saves current light switch data to save file.
function saveCurrentLightSwitchData (%saveFile)
{//echo("saveCurrentLightSwitchData()");
	// Write the light switch data.
	%lightSwitchCount = $switchList.getCount();
	%saveFile.WriteLine("lightSwitchData" SPC %lightSwitchCount);
	for (%i = 0; %i < %lightSwitchCount; %i++)
	{
		// Grab the light switch.
		%lightSwitch = $switchList.getObject(%i);
		
		// We save twelve (12) pieces of data.
		%saveFile.WriteLine("lightSwitchData"			SPC
							%lightSwitch.SceneLayer		SPC
							%lightSwitch.graph			SPC
							%lightSwitch.position		SPC
							%lightSwitch.scenegraph		SPC
							%lightSwitch.image			SPC
							%lightSwitch.visible		SPC
							%lightSwitch.size			SPC
							%lightSwitch.xIndex			SPC
							%lightSwitch.yIndex			SPC
							%lightSwitch.poweredOn		SPC
							%lightSwitch.destructible	SPC
							%lightSwitch.broken);
	}
}

// Loads the light switch data from save file.
function loadCurrentLightSwitchData ()
{//echo("loadCurrentLightSwitchData()");
	// Check load flag!
	if ($generateNewLevelFromLoad)
	{
		
		return;
	}
	
	// Sets the file to directory path: "C:\Users\<user>\AppData\Roaming\Steam Marines\"
	%filePath = getSaveGameFilePath();
	// The save file object.
	%saveFile = new fileobject();
	// Check the file open status.
	%ret = %saveFile.OpenForRead(%filePath);
	// Can't open the file.
	if (!%ret)
	{//echo("Bad save file!");
		error("Invalid save file!");
		return false;
	}
	
	// Find the light switch data.
	%totalLightSwitches = 0;
	for (%line = %saveFile.ReadLine(); !(%line $= ""); %line = %saveFile.ReadLine())
	{
		%word = getWord(%line, 0);
		if (%word $= "lightSwitchData")
		{
			%totalLightSwitches = getWord(%line, 1);
			break;
		}
	}
	
	// Loop through and fill data.
	for (%i = 0; %i < %totalLightSwitches; %i++)
	{
		// Get next line.
		%line = %saveFile.ReadLine();
		
		// Grab data.
		%SceneLayer = getWord(%line, 1);
		%graph = getWord(%line, 2);
		%position = getWord(%line, 3) SPC getWord(%line, 4);
		%scenegraph = getWord(%line, 5);
		%image = getWord(%line, 6);
		%visible = getWord(%line, 7);
		%size = getWord(%line, 8) SPC getWord(%line, 9);
		%xIndex = getWord(%line, 10);
		%yIndex = getWord(%line, 11);
		%poweredOn = getWord(%line, 12);
		%destructible = getWord(%line, 13);
		%broken = getWord(%line, 14);
		
		// Spawn light switch.
		%lightSwitch = new Sprite("light switch")
		{
			SceneLayer = %SceneLayer;
			graph = %graph;
			position = %position;
			scenegraph = levelSceneGraph;
			image = %image;
			visible = %visible;
			size = %size;
			xIndex = %xIndex;
			yIndex = %yIndex;
			poweredOn = %poweredOn;				// By default spawn light switchs powered off.
			destructible = %destructible;		// Flag if this dispenser is destructible or not; game critical light switchs should not be destructible!
			broken = %broken;					// By default light switchs are not broken.
			lightOverlay = %lightOverlay;		// Powered off means no light overlay mounted.
		};
		addObjectToScene(%lightSwitch);
		
		// Add light switch to list.
		$switchList.add(%lightSwitch);
	}
	
	// Don't close the file handle - that is the responsibility of the caller, function saveCurrentGame()!
}

// Saves current tile destruction data to save file.
function saveCurrentTileDestructionData (%saveFile)
{//echo("saveCurrentTileDestructionData()");
	// Write the tile destruction data.
	%tileDestructionCount = $destroyedTileList.getCount();
	%saveFile.WriteLine("tileDestructionData" SPC %tileDestructionCount);
	for (%i = 0; %i < %tileDestructionCount; %i++)
	{
		// Grab the destroyed tile indices.
		%destroyedTile = $destroyedTileList.getObject(%i);
		
		// We save two (2) pieces of data.
		%saveFile.WriteLine("tileDestructionData"		SPC
							%destroyedTile.xIndex		SPC
							%destroyedTile.yIndex);
	}
	
	// Don't close the file handle - that is the responsibility of the caller, function saveCurrentGame()!
}

// Loads the tile destruction data from save file.
function loadCurrentTileDestructionData ()
{//echo("loadCurrentTileDestructionData()");
	// Check load flag!
	if ($generateNewLevelFromLoad)
	{
		return;
	}
	
	// Sets the file to directory path: "C:\Users\<user>\AppData\Roaming\Steam Marines\"
	%filePath = getSaveGameFilePath();
	// The save file object.
	%saveFile = new fileobject();
	// Check the file open status.
	%ret = %saveFile.OpenForRead(%filePath);
	// Can't open the file.
	if (!%ret)
	{//echo("Bad save file!");
		error("Invalid save file!");
		return false;
	}
	
	// Find the tile destruction data.
	%destroyedTileCount = 0;
	for (%line = %saveFile.ReadLine(); !(%line $= ""); %line = %saveFile.ReadLine())
	{
		%word = getWord(%line, 0);
		if (%word $= "tileDestructionData")
		{
			%destroyedTileCount = getWord(%line, 1);
			break;
		}
	}
	
	// Loop through and fill data.
	for (%i = 0; %i < %destroyedTileCount; %i++)
	{
		// Get next line.
		%line = %saveFile.ReadLine();
		
		// Grab data.
		%xIndex = getWord(%line, 1);
		%yIndex = getWord(%line, 2);
		
		// Show tile destruction.
		showAdjacentTileDestruction(%xIndex, %yIndex);
	}
	
	// Don't close the file handle - that is the responsibility of the caller, function saveCurrentGame()!
}

// Saves current treasure chest data to save file.
function saveCurrentTreasureChestData (%saveFile)
{//echo("saveCurrentTreasureChestData()");
	// Write the treasure chest data.
	%treasureChestCount = $treasureChestList.getCount();
	%saveFile.WriteLine("treasureChestData" SPC %treasureChestCount);
	for (%i = 0; %i < %treasureChestCount; %i++)
	{
		// Grab the treasure chest indices.
		%treasureChest = $treasureChestList.getObject(%i);
		
		// We save two (2) pieces of data.
		%saveFile.WriteLine("treasureChestData"			SPC
							%treasureChest.xIndex		SPC
							%treasureChest.yIndex);
	}
	
	// Don't close the file handle - that is the responsibility of the caller, function saveCurrentGame()!
}

// Loads the treasure chest data from save file.
function loadCurrentTreasureChestData ()
{//echo("loadCurrentTreasureChestData()");
	// Check load flag!
	if ($generateNewLevelFromLoad)
	{
		return;
	}
	
	// Sets the file to directory path: "C:\Users\<user>\AppData\Roaming\Steam Marines\"
	%filePath = getSaveGameFilePath();
	// The save file object.
	%saveFile = new fileobject();
	// Check the file open status.
	%ret = %saveFile.OpenForRead(%filePath);
	// Can't open the file.
	if (!%ret)
	{//echo("Bad save file!");
		error("Invalid save file!");
		return false;
	}
	
	// Find the treasure chest data.
	%treasureChestCount = 0;
	for (%line = %saveFile.ReadLine(); !(%line $= ""); %line = %saveFile.ReadLine())
	{
		%word = getWord(%line, 0);
		if (%word $= "treasureChestData")
		{
			%treasureChestCount = getWord(%line, 1);
			break;
		}
	}
	
	// Loop through and fill data.
	for (%i = 0; %i < %treasureChestCount; %i++)
	{
		// Get next line.
		%line = %saveFile.ReadLine();
		
		// Grab data.
		%xIndex = getWord(%line, 1);
		%yIndex = getWord(%line, 2);
		
		// Spawn treasure chest.
		spawnTreasureChest(%xIndex, %yIndex);
	}
	
	// Don't close the file handle - that is the responsibility of the caller, function saveCurrentGame()!
}

// Saves current trap data to save file.
function saveCurrentTrapData (%saveFile)
{//echo("saveCurrentTrapData()");
	// Write the trap data.
	%trapCount = $trapList.getCount();
	%saveFile.WriteLine("trapData" SPC %trapCount);
	for (%i = 0; %i < %trapCount; %i++)
	{
		// Grab the trap indices.
		%trap = $trapList.getObject(%i);
		
		// We save four (4) pieces of data.
		%saveFile.WriteLine("trapData"			SPC
							%trap.xIndex		SPC
							%trap.yIndex		SPC
							%trap.trapType		SPC
							%trap.trapDamage);
	}
	
	// Don't close the file handle - that is the responsibility of the caller, function saveCurrentGame()!
}

// Loads the trap data from save file.
function loadCurrentTrapData ()
{//echo("loadCurrentTrapData()");
	// Check load flag!
	if ($generateNewLevelFromLoad)
	{
		return;
	}
	
	// Sets the file to directory path: "C:\Users\<user>\AppData\Roaming\Steam Marines\"
	%filePath = getSaveGameFilePath();
	// The save file object.
	%saveFile = new fileobject();
	// Check the file open status.
	%ret = %saveFile.OpenForRead(%filePath);
	// Can't open the file.
	if (!%ret)
	{//echo("Bad save file!");
		error("Invalid save file!");
		return false;
	}
	
	// Find the trap data.
	%trapCount = 0;
	for (%line = %saveFile.ReadLine(); !(%line $= ""); %line = %saveFile.ReadLine())
	{
		%word = getWord(%line, 0);
		if (%word $= "trapData")
		{
			%trapCount = getWord(%line, 1);
			break;
		}
	}
	
	// Loop through and fill data.
	for (%i = 0; %i < %trapCount; %i++)
	{
		// Get next line.
		%line = %saveFile.ReadLine();
		
		// Grab data.
		%xIndex = getWord(%line, 1);
		%yIndex = getWord(%line, 2);
		%trapType = getWord(%line, 3);
		%trapDamage = getWord(%line, 4);		// Unused for now!
		
		// Spawn trap.
		spawnTrap(%xIndex, %yIndex, %trapType);
	}
	
	// Don't close the file handle - that is the responsibility of the caller, function saveCurrentGame()!
}

// Saves current grating data to save file.
function saveCurrentGratingData (%saveFile)
{//echo("saveCurrentGratingData()");
	// Write the grating data.
	%gratingCount = $gratingList.getCount();
	%saveFile.WriteLine("gratingData" SPC %gratingCount);
	for (%i = 0; %i < %gratingCount; %i++)
	{
		// Grab the grating indices.
		%grating = $gratingList.getObject(%i);
		
		// We save four (4) pieces of data.
		%saveFile.WriteLine("gratingData"			SPC
							%grating.xIndex			SPC
							%grating.yIndex			SPC
							%grating.image			SPC
							%grating.frame);
	}
	
	// Don't close the file handle - that is the responsibility of the caller, function saveCurrentGame()!
}

// Loads the grating data from save file.
function loadCurrentGratingData ()
{//echo("loadCurrentGratingData()");
	// Check load flag!
	if ($generateNewLevelFromLoad)
	{
		return;
	}
	
	// Sets the file to directory path: "C:\Users\<user>\AppData\Roaming\Steam Marines\"
	%filePath = getSaveGameFilePath();
	// The save file object.
	%saveFile = new fileobject();
	// Check the file open status.
	%ret = %saveFile.OpenForRead(%filePath);
	// Can't open the file.
	if (!%ret)
	{//echo("Bad save file!");
		error("Invalid save file!");
		return false;
	}
	
	// Find the grating data.
	%gratingCount = 0;
	for (%line = %saveFile.ReadLine(); !(%line $= ""); %line = %saveFile.ReadLine())
	{
		%word = getWord(%line, 0);
		if (%word $= "gratingData")
		{
			%gratingCount = getWord(%line, 1);
			break;
		}
	}
	
	// Loop through and fill data.
	for (%i = 0; %i < %gratingCount; %i++)
	{
		// Get next line.
		%line = %saveFile.ReadLine();
		
		// Grab data.
		%xIndex = getWord(%line, 1);
		%yIndex = getWord(%line, 2);
		%image = getWord(%line, 3);
		%frame = getWord(%line, 4);
		
		// Spawn grating tile.
		%burst = false;
		if (%frame == 50)
		{
			%burst = true;
		}
		spawnGrating(%xIndex, %yIndex, %burst);
	}
	// Add grating steam venting animations.
	addSteamVentingAnimations();
	
	// Don't close the file handle - that is the responsibility of the caller, function saveCurrentGame()!
}

// Saves current CryoTube data to save file.
function saveCurrentCryoTubeData (%saveFile)
{//echo("saveCurrentCryoTubeData()");
	// Write the grating data.
	%cryoTubeCount = $CryoTubeList.getCount();
	%saveFile.WriteLine("cryoTubeData" SPC %cryoTubeCount);
	for (%i = 0; %i < %cryoTubeCount; %i++)
	{
		// Grab the grating indices.
		%cryoTube = $CryoTubeList.getObject(%i);
		
		// We save three (3) pieces of data.
		%saveFile.WriteLine("cryoTubeData"			SPC
							%cryoTube.xIndex		SPC
							%cryoTube.yIndex);
	}
	
	// Don't close the file handle - that is the responsibility of the caller, function saveCurrentGame()!
}

// Loads the CryoTube data from save file.
function loadCurrentCryoTubeData ()
{//echo("loadCurrentCryoTubeData()");
	// Check load flag!
	if ($generateNewLevelFromLoad)
	{
		return;
	}
	
	// Sets the file to directory path: "C:\Users\<user>\AppData\Roaming\Steam Marines\"
	%filePath = getSaveGameFilePath();
	// The save file object.
	%saveFile = new fileobject();
	// Check the file open status.
	%ret = %saveFile.OpenForRead(%filePath);
	// Can't open the file.
	if (!%ret)
	{//echo("Bad save file!");
		error("Invalid save file!");
		return false;
	}
	
	// Find the grating data.
	%cryoTubeCount = 0;
	for (%line = %saveFile.ReadLine(); !(%line $= ""); %line = %saveFile.ReadLine())
	{
		%word = getWord(%line, 0);
		if (%word $= "cryoTubeData")
		{
			%cryoTubeCount = getWord(%line, 1);
			break;
		}
	}
	
	// Loop through and fill data.
	for (%i = 0; %i < %cryoTubeCount; %i++)
	{
		// Get next line.
		%line = %saveFile.ReadLine();
		
		// Grab data.
		%xIndex = getWord(%line, 1);
		%yIndex = getWord(%line, 2);
		
		// Spawn grating tile.
		createCryoTubeAnimation(%xIndex, %yIndex);
	}
	
	// Don't close the file handle - that is the responsibility of the caller, function saveCurrentGame()!
}

// Saves current lockers data to save file.
function saveCurrentLockersData (%saveFile)
{//echo("saveCurrentLockersData()");
	// Write the lockers data.
	%lockersCount = $LockersList.getCount();
	%saveFile.WriteLine("lockersData" SPC %lockersCount);
	for (%i = 0; %i < %lockersCount; %i++)
	{
		// Grab the lockers.
		%lockers = $LockersList.getObject(%i);
		
		// We save ten (10) pieces of data.
		%saveFile.WriteLine("lockersData"			SPC
							%lockers.SceneLayer		SPC
							%lockers.graph			SPC
							%lockers.position		SPC
							%lockers.scenegraph		SPC
							%lockers.image			SPC
							%lockers.visible		SPC
							%lockers.size			SPC
							%lockers.xIndex			SPC
							%lockers.yIndex			SPC
							%lockers.opened);
	}
}

// Loads the lockers data from save file.
function loadCurrentLockersData ()
{//echo("loadCurrentLockersData()");
	// Check load flag!
	if ($generateNewLevelFromLoad)
	{
		return;
	}
	
	// Sets the file to directory path: "C:\Users\<user>\AppData\Roaming\Steam Marines\"
	%filePath = getSaveGameFilePath();
	// The save file object.
	%saveFile = new fileobject();
	// Check the file open status.
	%ret = %saveFile.OpenForRead(%filePath);
	// Can't open the file.
	if (!%ret)
	{//echo("Bad save file!");
		error("Invalid save file!");
		return false;
	}
	
	// Find the console data.
	%totalLockers = 0;
	for (%line = %saveFile.ReadLine(); !(%line $= ""); %line = %saveFile.ReadLine())
	{
		%word = getWord(%line, 0);
		if (%word $= "lockersData")
		{
			%totalLockers = getWord(%line, 1);
			break;
		}
	}
	
	// Loop through and fill data.
	for (%i = 0; %i < %totalLockers; %i++)
	{
		// Get next line.
		%line = %saveFile.ReadLine();
		
		// Grab data.
		%SceneLayer = getWord(%line, 1);
		%graph = getWord(%line, 2);
		%position = getWord(%line, 3) SPC getWord(%line, 4);
		%scenegraph = getWord(%line, 5);
		%image = getWord(%line, 6);
		%visible = getWord(%line, 7);
		%size = getWord(%line, 8) SPC getWord(%line, 9);
		%xIndex = getWord(%line, 10);
		%yIndex = getWord(%line, 11);
		%opened = getWord(%line, 12);
		
		// Spawn lockers.
		%lockers = new Sprite("lockers")
		{
			SceneLayer = %SceneLayer;
			graph = %graph;
			position = %position;
			scenegraph = levelSceneGraph;
			image = %image;
			visible = %visible;
			size = %size;
			xIndex = %xIndex;
			yIndex = %yIndex;
			opened = %opened;
		};
		addObjectToScene(%lockers);
		
		// Add lockers to list.
		$LockersList.add(%lockers);
	}
	
	// Don't close the file handle - that is the responsibility of the caller, function saveCurrentGame()!
}

// Saves current corpse data to save file.
function saveCurrentCorpseData (%saveFile)
{//echo("saveCurrentCorpseData()");
	// Write the corpse data.
	%corpseCount = $CorpseList.getCount();
	%saveFile.WriteLine("corpseData" SPC %corpseCount);
	for (%i = 0; %i < %corpseCount; %i++)
	{
		// Grab the corpse.
		%corpse = $CorpseList.getObject(%i);
		
		// We save ten (10) pieces of data.
		%saveFile.WriteLine("corpseData"			SPC
							%corpse.SceneLayer		SPC
							%corpse.graph			SPC
							%corpse.position		SPC
							%corpse.scenegraph		SPC
							%corpse.image			SPC
							%corpse.visible			SPC
							%corpse.size			SPC
							%corpse.xIndex			SPC
							%corpse.yIndex);
	}
}

// Loads the corpse data from save file.
function loadCurrentCorpseData ()
{//echo("loadCurrentCorpseData()");
	// Check load flag!
	if ($generateNewLevelFromLoad)
	{
		return;
	}
	
	// Sets the file to directory path: "C:\Users\<user>\AppData\Roaming\Steam Marines\"
	%filePath = getSaveGameFilePath();
	// The save file object.
	%saveFile = new fileobject();
	// Check the file open status.
	%ret = %saveFile.OpenForRead(%filePath);
	// Can't open the file.
	if (!%ret)
	{//echo("Bad save file!");
		error("Invalid save file!");
		return false;
	}
	
	// Find the corpse data.
	%totalCorpses = 0;
	for (%line = %saveFile.ReadLine(); !(%line $= ""); %line = %saveFile.ReadLine())
	{
		%word = getWord(%line, 0);
		if (%word $= "corpseData")
		{
			%totalCorpses = getWord(%line, 1);
			break;
		}
	}
	
	// Loop through and fill data.
	for (%i = 0; %i < %totalCorpses; %i++)
	{
		// Get next line.
		%line = %saveFile.ReadLine();
		
		// Grab data.
		%SceneLayer = getWord(%line, 1);
		%graph = getWord(%line, 2);
		%position = getWord(%line, 3) SPC getWord(%line, 4);
		%scenegraph = getWord(%line, 5);
		%image = getWord(%line, 6);
		%visible = getWord(%line, 7);
		%size = getWord(%line, 8) SPC getWord(%line, 9);
		%xIndex = getWord(%line, 10);
		%yIndex = getWord(%line, 11);
		
		// Spawn corpse.
		%corpse = new Sprite("corpse")
		{
			SceneLayer = %SceneLayer;
			graph = %graph;
			position = %position;
			scenegraph = levelSceneGraph;
			image = %image;
			visible = %visible;
			size = %size;
			xIndex = %xIndex;
			yIndex = %yIndex;
		};
		addObjectToScene(%corpse);
		
		// Add corpse to list.
		$CorpseList.add(%corpse);
	}
	
	// Don't close the file handle - that is the responsibility of the caller, function saveCurrentGame()!
}

// Saves current turret data to save file.
function saveCurrentTurretData (%saveFile)
{//echo("saveCurrentTurretData()");
	// Write the turret data.
	%turretCount = $sentryTurretList.getCount();
	%saveFile.WriteLine("turretData" SPC %turretCount);
	for (%i = 0; %i < %turretCount; %i++)
	{
		// Grab the turret.
		%turret = $sentryTurretList.getObject(%i);
		
		// We save eighteen (18) pieces of data.
		%saveFile.WriteLine("turretData"			SPC
							%turret.SceneLayer		SPC
							%turret.graph			SPC
							%turret.position		SPC
							%turret.scenegraph		SPC
							%turret.Animation		SPC
							%turret.visible			SPC
							%turret.size			SPC
							%turret.xIndex			SPC
							%turret.yIndex			SPC
							%turret.projectileType	SPC
							%turret.damage			SPC
							%turret.range			SPC
							%turret.accuracy		SPC
							%turret.ammo			SPC
							%turret.ammoPerShot		SPC
							%turret.facing);
	}
}

// Loads the turret data from save file.
function loadCurrentTurretData ()
{//echo("loadCurrentTurretData()");
	// Check load flag!
	if ($generateNewLevelFromLoad)
	{
		return;
	}
	
	// Sets the file to directory path: "C:\Users\<user>\AppData\Roaming\Steam Marines\"
	%filePath = getSaveGameFilePath();
	// The save file object.
	%saveFile = new fileobject();
	// Check the file open status.
	%ret = %saveFile.OpenForRead(%filePath);
	// Can't open the file.
	if (!%ret)
	{//echo("Bad save file!");
		error("Invalid save file!");
		return false;
	}
	
	// Find the turret data.
	%totalTurrets = 0;
	for (%line = %saveFile.ReadLine(); !(%line $= ""); %line = %saveFile.ReadLine())
	{
		%word = getWord(%line, 0);
		if (%word $= "turretData")
		{
			%totalTurrets = getWord(%line, 1);
			break;
		}
	}
	
	// Loop through and fill data.
	for (%i = 0; %i < %totalTurrets; %i++)
	{
		// Get next line.
		%line = %saveFile.ReadLine();
		/*%saveFile.WriteLine("turretData"			SPC
							%turret.SceneLayer		SPC
							%turret.graph			SPC
							%turret.position		SPC
							%turret.scenegraph		SPC
							%turret.Animation		SPC
							%turret.visible			SPC
							%turret.size			SPC
							%turret.xIndex			SPC
							%turret.yIndex			SPC
							%turret.projectileType	SPC
							%turret.damage			SPC
							%turret.range			SPC
							%turret.accuracy		SPC
							%turret.ammo			SPC
							%turret.ammoPerShot		SPC
							%turret.facing);*/
		
		// Grab data.
		%SceneLayer = getWord(%line, 1);
		%graph = getWord(%line, 2);
		%position = getWord(%line, 3) SPC getWord(%line, 4);
		%scenegraph = getWord(%line, 5);
		%animation = getWord(%line, 6);
		%visible = getWord(%line, 7);
		%size = getWord(%line, 8) SPC getWord(%line, 9);
		%xIndex = getWord(%line, 10);
		%yIndex = getWord(%line, 11);
		%projectileType = getWord(%line, 12);
		%damage = getWord(%line, 13);
		%range = getWord(%line, 14);
		%accuracy = getWord(%line, 15);
		%ammo = getWord(%line, 16);
		%ammoPerShot = getWord(%line, 17);
		%facing = getWord(%line, 18);
		
		// Spawn turret.
		%turret = new Sprite("turret")
		{
			SceneLayer = %SceneLayer;
			graph = %graph;
			position = %position;
			scenegraph = levelSceneGraph;
			Animation = %animation;
			visible = %visible;
			size = %size;
			xIndex = %xIndex;
			yIndex = %yIndex;
			projectileType = %projectileType;
			damage = %damage;
			range = %range;
			accuracy = %accuracy;
			ammo = %ammo;
			ammoPerShot = %ammoPerShot;
			facing = %facing;
		};
		addObjectToScene(%turret);
		
		// Add turret to list.
		$sentryTurretList.add(%turret);
	}
	
	// Don't close the file handle - that is the responsibility of the caller, function saveCurrentGame()!
}