// Handles Environment Interactions.
// WorthlessBums 2012.


// Returns true iff the active character can interact with environment.
function canEnvironmentInteract ()
{//echo("canEnvironmentInteract()");
	// Check the tile adjacent in the facing direction.
	%xIndex = $playerSquad[$activeCharacter].xIndex;
	%yIndex = $playerSquad[$activeCharacter].yIndex;
	// Alter indices based on facing
	switch ($playerSquad[$activeCharacter].facing)
	{
		case $northDirection:	%yIndex--;
		case $southDirection:	%yIndex++;
		case $eastDirection:	%xIndex++;
		case $westDirection:	%xIndex--;
	}
	// Check if tile is flagged as an open door.
	if ($mazeRoom[%xIndex, %yIndex].status == -4)
	{
		return true;
	}
	
	// Check if the character is facing north to activate a console.
	if ($playerSquad[$activeCharacter].facing == $southDirection)
	{
		// Check if there is a console.
		for (%i = 0; %i < $consoleList.getCount(); %i++)
		{
			// Grab the console.
			%console = $consoleList.getObject(%i);
			if (%console.xIndex == $playerSquad[$activeCharacter].xIndex	&&
				%console.yIndex == $playerSquad[$activeCharacter].yIndex)
			{
				// Check if the console hasn't been used yet.
				if (!%console.broken	&&
					%console.image !$= "Sprites:ConsoleOn")
				{
					return true;
				}
			}
		}
	}
		
	// Check if there is a dispenser.
	for (%i = 0; %i < $dispenserList.getCount(); %i++)
	{
		// Grab the dispenser.
		%dispenser = $dispenserList.getObject(%i);
		if (%dispenser.xIndex == %xIndex	&&
			%dispenser.yIndex == %yIndex)
		{
			return true;
		}
	}
		
	// Check if the character is facing north to activate a switch.
	if ($playerSquad[$activeCharacter].facing == $northDirection)
	{
		// Check if there is a switch.
		for (%i = 0; %i < $switchList.getCount(); %i++)
		{
			// Grab the switch.
			%switchSpawn = $switchList.getObject(%i);
			if (%switchSpawn.xIndex == %xIndex	&&
				%switchSpawn.yIndex == %yIndex)
			{
				return true;
			}
		}
	}
	
	return false;
}
// Interact with environment.
function environmentInteract (%direction)
{//echo("environmentInteract()");
	// Check the tile adjacent in the facing direction.
	%xIndex = $playerSquad[$activeCharacter].xIndex;
	%yIndex = $playerSquad[$activeCharacter].yIndex;
	// Alter indices based on facing or the specified direction parameter.
	if (%direction != 0)
	{
		switch (%direction)
		{
			case $northDirection:	%yIndex--;
			case $southDirection:	%yIndex++;
			case $eastDirection:	%xIndex++;
			case $westDirection:	%xIndex--;
		}
	}
	else
	{
		switch ($playerSquad[$activeCharacter].facing)
		{
			case $northDirection:	%yIndex--;
			case $southDirection:	%yIndex++;
			case $eastDirection:	%xIndex++;
			case $westDirection:	%xIndex--;
		}
	}
	// Check if tile is flagged as an open door.
	if ($mazeRoom[%xIndex, %yIndex].status == -4)
	{
		closeDoor();
		return;
	}
	
	// Check action points.
	%actionPointCost = getActionPointCost(12);
	
	// We have enough AP to close a door!
	if ($playerSquad[$activeCharacter].currentActionPoints >= %actionPointCost)
	{//echo("%direction =" SPC %direction);
		// Check if the character is facing north to activate lockers or a console.
		if (%direction == $southDirection)
		{//echo("NORTH DIRECTION");
			// Check if there is a console.
			for (%i = 0; %i < $consoleList.getCount(); %i++)
			{
				// Grab the console.
				%console = $consoleList.getObject(%i);
				if (%console.xIndex == $playerSquad[$activeCharacter].xIndex	&&
					%console.yIndex == $playerSquad[$activeCharacter].yIndex)
				{//echo("using console at: " @ %console.xIndex SPC %console.yIndex);
					// Make sure the console isn't broken.
					if (%console.broken)
					{
						// Update event log.
						updateEventText($whiteColor @ "This console is broken" @ $defaultColor @ ".");
					}
					// Make sure the console hasn't been used already! (INFINITE MOOLA!)
					else if (%console.image $= "Sprites:ConsoleOn")
					{
						// Don't use it!
					}
					else
					{
						// Increment total Consoles Used!
						$GlobalStats.totalConsolesUsed++;
						
						// Play use console sound effect.
						playAudio("Audio:consoleUse", EffectsAudioVolume.value);
						// Use the console.
						%console.image = "Sprites:ConsoleOn";
						// Deduct the appropriate amount of action points for this action.
						setCurrentActionPoints($activeCharacter, $playerSquad[$activeCharacter].currentActionPoints - %actionPointCost);
						// Update readout.
						initializeReadout();
						scheduleMonsterTurn();
						// Pop up with dialogue!
						setIndividualDialoguePopup($playerSquad[$activeCharacter], getConsoleDialogue(%console.dialogueId), "dialogue");
						
						// Special effects!
						triggerConsoleActivation(%console.dialogueId);
						
						// Check for Engineering class talent "Hackery"!
						if ($playerSquad[$activeCharacter].characterClass == 4	&&
							getWord($playerSquad[$activeCharacter].talents, 3) == 1)
						{//echo("HACKERY DETECTED!");
							triggerHackInfo(0);
						}
					}
					// Face character north.
					setSquadMemberFacing($southDirection, $playerSquad[$activeCharacter]);
					return;
				}
			}
			// Check if there are Lockers.
			for (%i = 0; %i < $LockersList.getCount(); %i++)
			{//echo("checking Lockers " @ %i);
				// Grab the lockers.
				%lockers = $LockersList.getObject(%i);
				if (%lockers.xIndex == $playerSquad[$activeCharacter].xIndex	&&
					%lockers.yIndex == $playerSquad[$activeCharacter].yIndex)
				{//echo("using Lockers at: " @ %lockers.xIndex SPC %lockers.yIndex);
					// Make sure the lockers isn't already open.
					if (%lockers.opened)
					{
						updateEventText($whiteColor @ "These lockers are open..." @ $defaultColor @ ".");
						setIndividualDialoguePopup($playerSquad[$activeCharacter], "Nothing in here.", "dialogue");
					}
					// Make sure the lockers hasn't been used already!
					else if (%lockers.image $= getLockersOpenedSprites())
					{
						setIndividualDialoguePopup($playerSquad[$activeCharacter], "Nothing else in here.", "dialogue");
					}
					else
					{
						$GlobalStats.totalLonsolesUsed++;
						playAudio("Audio:consoleUse", EffectsAudioVolume.value);
						%lockers.image = getLockersOpenedSprites();
						%lockers.opened = true;
						setCurrentActionPoints($activeCharacter, $playerSquad[$activeCharacter].currentActionPoints - %actionPointCost);
						initializeReadout();
						scheduleMonsterTurn();
						triggerLockersActivation();
					}
					setSquadMemberFacing($southDirection, $playerSquad[$activeCharacter]);
					return;
				}
			}
		}
		
		// Check if there is a dispenser.
		for (%i = 0; %i < $dispenserList.getCount(); %i++)
		{
			// Grab the dispenser.
			%dispenser = $dispenserList.getObject(%i);
			if (%dispenser.xIndex == %xIndex	&&
				%dispenser.yIndex == %yIndex)
			{
				// Make sure the dispenser isn't broken.
				if (%dispenser.broken)
				{
					// Update event log.
					updateEventText($whiteColor @ "This dispenser is broken" @ $defaultColor @ ".");
				}
				else
				{
					// Increment total Dispensers Used!
					$GlobalStats.totalDispensersUsed++;
					// Use the dispenser.
					if (%dispenser.image $= getBigDispenserOnSprites())
					{
						%dispenser.image = getBigDispenserOffSprites();
					}
					else if (%dispenser.image $= getSmallDispenserOnSprites())
					{
						%dispenser.image = getSmallDispenserOffSprites();
					}
					else
					{
						return;
					}
					// Remove light overlay!
					(%dispenser.lightOverlay).safeDelete();
					// Deduct the appropriate amount of action points for this action.
					setCurrentActionPoints($activeCharacter, $playerSquad[$activeCharacter].currentActionPoints - %actionPointCost);
					// Update readout.
					initializeReadout();
					scheduleMonsterTurn();
					// Add random ammo amount.
					$playerSquad[$activeCharacter].ammo += getRandom(1, 3);
					// Play sound effect.
					playAudio("Audio:dispenserUse", EffectsAudioVolume.value);
					// Pop up with dialogue!
					setIndividualDialoguePopup($playerSquad[$activeCharacter], "More ammo here!", "dialogue");
					// Update inventory tab information.
					updateInventoryTabInformation();
				}
				return;
			}
		}
		
		
		
		// Check if the character is facing north to activate a switch.
		if ($playerSquad[$activeCharacter].facing == $northDirection)
		{
			// Check if there is a switch.
			for (%i = 0; %i < $switchList.getCount(); %i++)
			{
				// Grab the switch.
				%switchSpawn = $switchList.getObject(%i);
				if (%switchSpawn.xIndex == %xIndex	&&
					%switchSpawn.yIndex == %yIndex)
				{
					// Make sure the switch isn't broken.
					if (%switchSpawn.broken)
					{
						// Update event log.
						updateEventText($whiteColor @ "This switch is broken" @ $defaultColor @ ".");
					}
					else
					{
						// Increment total Light Switches Used!
						$GlobalStats.totalLightSwitchesUsed++;
						
						// Use the switch.
						if (%switchSpawn.imagemap $= "SwitchOnImageMap")
						{
							%switchSpawn.imagemap = "SwitchOffImageMap";
						}
						else
						{
							%switchSpawn.imagemap = "SwitchOnImageMap";
						}
						// Deduct the appropriate amount of action points for this action.
						setCurrentActionPoints($activeCharacter, $playerSquad[$activeCharacter].currentActionPoints - %actionPointCost);
						// Update readout.
						initializeReadout();
						scheduleMonsterTurn();
						
						// Switch affects all nearby lights!
						for (%i = 0; %i < $lightList.getCount(); %i++)
						{
							%light = $lightList.getObject(%i);
							if (mAbs(%light.xIndex - %xIndex) <= 5	&&
								mAbs(%light.yIndex - %yIndex) <= 5)
							{
								if (%switchSpawn.imagemap $= "SwitchOffImageMap")
								{
									(%light.lightSource).setVisible(0);
								}
								else
								{
									(%light.lightSource).setVisible(1);
								}
							}
						}
					}
					
					
					return;
				}
			}
		}
	}
}

// Returns true iff there is a console at the specified indices.
function tileHasConsole (%xIndex, %yIndex)
{//echo("tileHasConsole()");
	for (%i = 0; %i < $consoleList.getCount(); %i++)
	{
		%console = $consoleList.getObject(%i);
		if (%console.xIndex == %xIndex	&&
			%console.yIndex == %yIndex)
		{
			return true;
		}
	}
	return false;
}

// Returns true iff there are lockers at the specified indices.
function tileHasLockers (%xIndex, %yIndex)
{//echo("tileHasLockers()");
	for (%i = 0; %i < $LockersList.getCount(); %i++)
	{
		%lockers = $LockersList.getObject(%i);
		if (%lockers.xIndex == %xIndex	&&
			%lockers.yIndex == %yIndex)
		{
			return true;
		}
	}
	return false;
}

// Returns true iff there is a dispenser at the specified indices.
function tileHasDispenser (%xIndex, %yIndex)
{//echo("tileHasDispenser()");
	for (%i = 0; %i < $dispenserList.getCount(); %i++)
	{
		%dispenser = $dispenserList.getObject(%i);
		if (%dispenser.xIndex == %xIndex	&&
			%dispenser.yIndex == %yIndex)
		{
			return true;
		}
	}
	return false;
}

// Returns a dispenser indeix at the specified indices, -1 otherwise
function hasDispenser (%xIndex, %yIndex)
{//echo("hasDispenser()");
	for (%i = 0; %i < $dispenserList.getCount(); %i++)
	{
		%dispenser = $dispenserList.getObject(%i);
		if (%dispenser.xIndex == %xIndex	&&
			%dispenser.yIndex == %yIndex)
		{
			return %i;
		}
	}
	return -1;
}

// Spawns consoles.
function spawnConsoles ()
{//echo("spawnConsoles()");
	if ($overworldLocation $= "Alien Deck")
	{
		return;
	}
	// Loop through the map and find places to put consoles.
	for (%i = 0; %i < $mazeDimension; %i++)
	{
		for (%j = 0; %j < $mazeDimension; %j++)
		{
			if (canPlaceObjectBelow(%i, %j))
			{//echo("looking to place console!");
				// Check to make sure there is a floor tile south of this tile.
				if (!isObject($mazeRoom[%i, %j - 1]))
				{
					// Make sure there are no adjacent doors East and West! (Just check for obstructing tiles for now.)
					if (!isObject($mazeRoom[%i + 1, %j - 1])	&&
						!isObject($mazeRoom[%i - 1, %j - 1])	&&
						tileIsClearOfUnits(%i, %j))
					{//echo("south space clear!");
						// Randomize chance to spawn a console.
						%consoleChance = getRandom(1, 100);
						if (%consoleChance <= $consoleSpawnChance)
						{//echo("spawning console at position: " @ $mazeRoom[%i, %j].getPosition());
							// Spawn console.
							%console = new Sprite("console")
							{
								SceneLayer = $ConsoleLayer;
								graph = $ConsoleGroup;
								position = getWord(getTilePositionFromIndices(%i, %j), 0) SPC getWord(getTilePositionFromIndices(%i, %j - 1), 1) + 2;
								scenegraph = levelSceneGraph;
								image = "Sprites:ConsoleOff";	// By default spawn consoles powered off.
								visible = true;
								size = "4 4";
								xIndex = %i;
								yIndex = %j - 1;
								poweredOn = false;					// By default spawn conosles powered off.
								destructible = true;				// Flag if this console is destructible or not; game critical consoles should not be destructible!
								broken = false;						// By default consoles are not broken.
								dialogueID = getRandomConsoleDialogueID();
							};
							addObjectToScene(%console);
							// Add dialogue.
							%console.dialogue = getConsoleDialogue(%console.dialogueID);
							// Add console to list.
							$consoleList.add(%console);
						}
					}
				}
			}
		}
	}
}

// Spawns Lockers.
// NOTE: Lockers spawn after consoles and light switches so check for overlap!
function spawnLockers ()
{//echo("spawnLockers()");
	// Loop through the map and find places to put Lockers.
	for (%i = 0; %i < $mazeDimension; %i++)
	{
		for (%j = 0; %j < $mazeDimension; %j++)
		{
			if (canPlaceObjectBelow(%i, %j))
			{//echo("can place object below!");
				// Check to make sure there is a floor tile south of this tile.
				if (!isObject($mazeRoom[%i, %j - 1]))
				{//echo("south tile clear!");
					// Make sure there are no adjacent doors East and West! (Just check for obstructing tiles for now.)
					if (!isObject($mazeRoom[%i + 1, %j - 1])	&&
						!isObject($mazeRoom[%i - 1, %j - 1])	&&
						tileIsClearOfUnits(%i, %j)				&&
						tileClearOfConsoles(%i, %j - 1))			// Check for consoles - ignore switches for now!
					{
						%lockersChance = getRandom(1, 100);
						if (%lockersChance <= 100)//$LockersSpawnChance)
						{//echo("spawning LOCKERS at indices: " @ %i SPC %j);
							%lockers = new Sprite("Lockers")
							{
								SceneLayer = $LockersLayer;
								graph = $LockersGroup;
								position = getWord(getTilePositionFromIndices(%i, %j), 0) SPC getWord(getTilePositionFromIndices(%i, %j - 1), 1) + 2.2;
								scenegraph = levelSceneGraph;
								image = getLockersClosedSprites();	// By default spawn Lockers closed..
								visible = true;
								size = "4 4";
								xIndex = %i;
								yIndex = %j - 1;
								opened = false;
							};
							addObjectToScene(%lockers);
							$LockersList.add(%lockers);
						}
					}
				}
			}
		}
	}
}

// Gets a random console dialogue ID.
function getRandomConsoleDialogueID ()
{//echo("getRandomConsoleDialogueID()");
	return getRandom(0, 40);
}

// Returns the console dialogue string for an ID.
function getConsoleDialogue(%id)
{//echo"getConsoleDialogue()");
	switch (%id)
	{
		case  0:	%consoleDialogue = "This console seems corrupted.";
		case  1:	%consoleDialogue = "\"Steamy Encounters in Engineering.\" Nice.";
		case  2:	%consoleDialogue = "Zoozle Mapping service engaged, admired customer!";
		case  3:	%consoleDialogue = "\"Directed Energy Weapons are the future.\" Paid for by Lazer Corp.";
		case  4:	%consoleDialogue = "Captain Kraft's fine Italian cuisine located in the lounge.";
		case  5:	%consoleDialogue = "You can barely read the screen.";
		case  6:	%consoleDialogue = "Emails. Lots of emails.";
		case  7:	%consoleDialogue = "Looks like a requisition for chainsaws.";
		case  8:	%consoleDialogue = "Looks like a prototype for a new plasma cutter.";
		case  9:	%consoleDialogue = "\"Armor so smart a monkey could use it.\" Hey!";
		case 10:	%consoleDialogue = "Visit Pixie's Boutique on the Engineering Deck!";
		case 11:	%consoleDialogue = "\"Bigger. Stronger. Longer.\" What about faster?";
		case 12:	%consoleDialogue = "Vote Space Pope!";
		case 13:	%consoleDialogue = "This looks like that popular roguelikelikeish video game.";
		case 14:	%consoleDialogue = "Zombies on a space ship. Yeah right.";
		case 15:	%consoleDialogue = "Space Sardines Inc. closes shop after the decompression incident.";
		case 16:	%consoleDialogue = "It seems like something could crawl out of this screen...";
		case 17:	%consoleDialogue = "\"Rules of engagement policy, v5.1. Never engage.\"";
		case 18:	%consoleDialogue = "\"Rules of engagement policy, v5.2. Always engage.\"";
		case 19:	%consoleDialogue = "Too bad we can't message the fleet from here.";
		case 20:	%consoleDialogue = "Most marines are still asleep...";
		case 21:	%consoleDialogue = "Foreign material detected on the Medical Deck.";
		case 22:	%consoleDialogue = "... system shutting down...";
		case 23:	%consoleDialogue = "The ship is drifting. I can see that from the portholes...";
		case 24:	%consoleDialogue = "If I could just wake the rest of the corps from here...";
		case 25:	%consoleDialogue = "\"THE END OF TIMES IS HERE.\" You being dramatic, man.";
		case 25:	%consoleDialogue = "*taptaptap* Blasted human tech.";
		case 26:	%consoleDialogue = "Porn everywhere. Disgusting.";
		case 27:	%consoleDialogue = "Porn everywhere... nah.";
		case 28:	%consoleDialogue = "Someone's kids back home...";
		case 29:	%consoleDialogue = "Navy personnel files. Not useful.";
		case 30:	%consoleDialogue = "Looks like the crew sounded the alarm from the bridge.";
		case 31:	%consoleDialogue = "Parts of the ship are still in human hands...";
		case 32:	%consoleDialogue = "\"Survivors are directed to bunker in the deck elevators.\"";
		case 33:	%consoleDialogue = "\"Marines directed to sweep each deck.\" Working on it.";
		case 34:	%consoleDialogue = "\"Marines directed to wash the bulkheads.\" ... I'll get right on that.";
		case 35:	%consoleDialogue = "Most of the ship levels have been cut off due to power loss.";
		case 36:	%consoleDialogue = "All decks still accessible from the elevator. Good to know.";
		case 37:	%consoleDialogue = "\"Pneumatic Glove MKII is banned for onboard use.\" Whoops.";
		case 38:	%consoleDialogue = "\"Invaders ranked as class 3 threat. Recommend evasion.\"";
		case 39:	%consoleDialogue = "Non-combatant body count is piling up. Damn.";
		case 40:	%consoleDialogue = "\"Remember, the Lieutenant's birthday is on Sunday!\"";
		case 41:	%consoleDialogue = "\"Multipass!\"";
	}
	
	// Return dialogue string.
	return %consoleDialogue;
}

// Returns true iff the selected tile is a wall that we can place objects (e.g. dispensers) below.
function canPlaceObjectBelow (%i, %j)
{//echo("canPlaceObjectBelow()");
	if ($mazeRoom[%i, %j].frame == 14	||
		$mazeRoom[%i, %j].frame == 15	||
		$mazeRoom[%i, %j].frame == 27	||
		$mazeRoom[%i, %j].frame == 28	||
		$mazeRoom[%i, %j].frame == 29	||
		$mazeRoom[%i, %j].frame == 36	||
		$mazeRoom[%i, %j].frame == 37	||
		$mazeRoom[%i, %j].frame == 42	||
		$mazeRoom[%i, %j].frame == 45	||
		$mazeRoom[%i, %j].frame == 46	||
		$mazeRoom[%i, %j].frame == 54	||
		$mazeRoom[%i, %j].frame == 55	||
		$mazeRoom[%i, %j].frame == 56	||
		$mazeRoom[%i, %j].frame == 57	||
		$mazeRoom[%i, %j].frame == 58	||
		$mazeRoom[%i, %j].frame == 59	||
		$mazeRoom[%i, %j].frame == 60	||
		$mazeRoom[%i, %j].frame == 61	||
		$mazeRoom[%i, %j].frame == 67	||
		$mazeRoom[%i, %j].frame == 73	||
		$mazeRoom[%i, %j].frame == 74	||
		$mazeRoom[%i, %j].frame == 77)
	{
		return true;
	}
	return false;
}

// Spawns dispensers.
function spawnDispensers ()
{//echo("spawnDispensers()");
	// Loop through the map and find places to put consoles.
	for (%i = 0; %i < $mazeDimension; %i++)
	{
		for (%j = 0; %j < $mazeDimension; %j++)
		{
			// We currently only place dispensers on the floor tiles south of horizontal wall tiles!
			if (canPlaceObjectBelow(%i, %j))
			{//echo("south tile free!");
				// Check to make sure there is a floor tile south of this tile.
				if (!isObject($mazeRoom[%i, %j + 1]))
				{//echo("tile below is floor!");
					// Make sure there are no adjacent doors East and West! (Just check for obstructing tiles for now.)
					if (!isObject($mazeRoom[%i + 1, %j - 1])	&&
						!isObject($mazeRoom[%i - 1, %j - 1]))
					{//echo("no flanking doors!");
						// Randomize chance to spawn a dispenser.
						%dispenserChance = getRandom(1, 100);
						if (%dispenserChance <= 100)//$dispenserSpawnChance)
						{//echo("spawning dispenser at" SPC %i SPC %j);
						//echo("tileIsClearOfObstructions(" @ %i @ ", " @ %j @ ") =" SPC tileIsClearOfObstructions(%i, %j));
						//echo(tileHasConsole(%i, %j + 1));
							// Make sure there isn't already a console here!
							if (//!tileHasConsole(%i, %j + 1)	&&
								tileIsClearOfObstructions(%i, %j - 1)	&&
								tileClearOfConsoles(%i, %j + 1)			&&	// Don't spawn on top of consoles!
								tileClearOfConsoles(%i, %j))				// Don't spawn on top of consoles!
							{//echo("SPAWNED DISPENSER!");
								// Determine big or small dispenser.
								%dispenserSize = getRandom(0, 1);
								%image = "";
								if (%dispenserSize)
								{
									%image = getBigDispenserOnSprites();		// By default spawn dispensers powered on.
								}
								else
								{
									%image = getSmallDispenserOnSprites();		// By default spawn dispensers powered on.
								}
								// Spawn dispenser.
								%dispenser = new Sprite("dispenser")
								{
									SceneLayer = $DispenserLayer;
									position = getWord(getTilePositionFromIndices(%i, %j), 0) SPC getWord(getTilePositionFromIndices(%i, %j - 1), 1);
									scenegraph = levelSceneGraph;
									image = %image;
									visible = true;
									size = "4 4";
									xIndex = %i;
									yIndex = %j - 1;
									poweredOn = true;					// By default spawn dispensers powered on.
									destructible = true;				// Flag if this dispenser is destructible or not; game critical dispensers should not be destructible!
									broken = false;						// By default dispensers are not broken.
									lightOverlay = null;				// Powered off means no light overlay mounted.
								};
								addObjectToScene(%dispenser);
								// Attach light overlay!
								%dispenserLight = new Sprite("dispenser light")
								{
									SceneLayer = $DispenserLayer;
									position = getWord(%dispenser.getPosition(), 0) SPC getWord(%dispenser.getPosition(), 1) + 0.75;
									scenegraph = levelSceneGraph;
									imagemap = "ConsoleDispenserTileLightImageMap";
									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;
								// Add dispenser to list.
								$dispenserList.add(%dispenser);
								//echo($dispenserList.getcount());
							}
						}
					}
				}
			}
		}
	}
}

// Spawns switches.
function spawnSwitches ()
{//echo("spawnSwitches()");
	// Loop through the map and find places to put consoles.
	for (%i = 0; %i < $mazeDimension; %i++)
	{
		for (%j = 0; %j < $mazeDimension; %j++)
		{
			// Horizontal Wall tiles start with "WallThick". Why? Ask Detocroix, I dunno.
			%subStr = getSubStr($mazeRoom[%i, %j].imagemap, 0, 9);
			//echo("%subStr =" SPC %subStr);
			if (canPlaceObjectBelow(%i, %j))
			{//echo("found" SPC %subStr);
				// Check to make sure there is a floor tile south of this tile.
				if (!isObject($mazeRoom[%i, %j + 1]))
				{
					// Make sure there are no adjacent doors East and West! (Just check for obstructing tiles for now.)
					if (!isObject($mazeRoom[%i + 1, %j + 1])	&&
						!isObject($mazeRoom[%i - 1, %j + 1]))
					{
						// Randomize chance to spawn a switch.
						%switchChance = getRandom(1, 100);
						if (%switchChance <= $switchSpawnChance)
						{//echo("spawning switchSpawn at position: " @ $mazeRoom[%i, %j].getPosition());
							// Make sure there isn't already a console or switchSpawn here!
							if (!tileHasConsole(%i, %j + 1)	&&
								!tileHasDispenser(%i, %j + 1))
							{
								// Only spawn switches near lights.
								%spawnLight = false;
								for (%z = 0; %z < $lightList.getCount(); %z++)
								{
									%light = $lightList.getObject(%z);
									if (mAbs(%light.xIndex - %i) <= 5	&&
										mAbs(%light.yIndex - %j) <= 5)
									{
										%spawnLight = true;
									}
								}
								if (%spawnLight)
								{/*
									// Switch imagemap.
									%imageMap = "SpritesSwitchOn";		// By default spawn dispensers powered off.
									// Spawn switchSpawn.
									%switchSpawn = new Sprite("switchSpawn")
									{
										SceneLayer = $switchLayer;
										graph = $switchGroup;
										position = getWord($mazeRoom[%i, %j].getPosition(), 0) SPC getWord($mazeRoom[%i, %j].getPosition(), 1) + 0.5;
										scenegraph = levelSceneGraph;
										image = %imageMap;
										visible = true;
										size = "4 7";
										xIndex = %i;
										yIndex = %j;
										poweredOn = false;					// By default spawn dispensers powered off.
										destructible = true;				// Flag if this switchSpawn is destructible or not; game critical dispensers should not be destructible!
										broken = false;						// By default dispensers are not broken.
									};
									addObjectToScene(%switchSpawn);
									// Mount switch to the wall tile.
									//%switchSpawn.mount($mazeRoom[%i, %j], 0.0, 0.5, 50.0, true, true, true, true);
									// Add switchSpawn to list.
									$switchList.add(%switchSpawn);*/
								}
							}
						}
					}
				}
			}
		}
	}
}

// Returns true iff the tile is clear of obstructions.
function tileIsClearOfObstructions (%xIndex, %yIndex)
{//echo("tileIsClearOfObstructions()");
	if ((!isObject($mazeRoom[%xIndex, %yIndex])		|| $mazeRoom[%xIndex, %yIndex].status == -4)	&&
		tileClearOfSquadMembers(%xIndex, %yIndex)	&&
		tileClearOfMonsters(%xIndex, %yIndex)		&&
		tileClearOfTreasure(%xIndex, %yIndex)		&&
		tileClearOfDispensers(%xIndex, %yIndex)		&&
		tileClearOfBarrels(%xIndex, %yIndex)		&&
		!isSpaceTile (%xIndex, %yIndex))
	{//echo("TRUE!");
		return true;
	}//echo("FALSE!");
	return false;
}

// Checks if the specified tile is clear of consoles.
function tileClearOfConsoles (%xIndex, %yIndex)
{//echo("tileClearOfConsoles()");
	// Make sure $consoleList exists.
	if (!isObject($consoleList)	||
		$consoleList.getCount() <= 0)
	{
		return true;
	}
	// Loop through $consoleList and check their positions.
	for (%i = 0; %i < $consoleList.getCount(); %i++)
	{
		// Get the console.
		%console = ($consoleList.getObject(%i));
		// Check the console position against the specified tile position.
		if (%xIndex == %console.xIndex	&&
			%yIndex == %console.yIndex)
		{
			return false;
		}
	}
	return true;
}

// Checks if the specified tile is clear of dispensers.
function tileClearOfDispensers (%xIndex, %yIndex)
{//echo("tileClearOfDispensers()");
	// Make sure $dispenserList exists.
	if (!isObject($dispenserList)	||
		$dispenserList.getCount() <= 0)
	{
		return true;
	}
	// Loop through $dispenserList and check their positions.
	for (%i = 0; %i < $dispenserList.getCount(); %i++)
	{
		// Get the dispenser.
		%dispenser = ($dispenserList.getObject(%i));
		
		// Check the dispenser position against the specified tile position.
		if (%xIndex == %dispenser.xIndex	&&
			%yIndex == %dispenser.yIndex)
		{
			return false;
		}
	}
	return true;
}

// Checks if the specified tile is clear of dispensers chests.
function tileClearOfBarrels (%xIndex, %yIndex)
{//echo("tileClearOfBarrels()");
	// Make sure $barrelList exists.
	if (!isObject($barrelList)	||
		$barrelList.getCount() <= 0)
	{
		return true;
	}
	// Loop through $barrelList and check there positions.
	for (%i = 0; %i < $barrelList.getCount(); %i++)
	{
		// Get the barrel.
		%barrel = ($barrelList.getObject(%i));
		
		// Check the barrel position against the specified tile position.
		if (%xIndex == %barrel.xIndex	&&
			%yIndex == %barrel.yIndex)
		{
			return false;
		}
	}
	return true;
}