-- Carnival.levelgen
playersExist = {}
registeredPlayers = {}
registeredHealthPacks = {}
playersInSwords = {}
registeredZoneSwords = {}
snowRes = {} 

testObj = levelgen:findObjectById(100)

basicSwordGeom = {
	point.new(0, 0),  -- Helper point to make it easy to start where the middle of the sword end is
	point.new(0, -10),
	point.new(30, -10),
	point.new(40, -50),
	point.new(40, -10),
	point.new(250, 0),
	point.new(40, 10),
	point.new(40, 50),
	point.new(30, 10),
	point.new(0, 10),
}

cottonCandyGeom = {
	point.new(0,0),
	point.new(0, -51),
	point.new(19.5, -48),
	point.new(30, -37),
	point.new(41, -17),
	point.new(41, 7),
	point.new(30, 29),
	point.new(6.5, 37),
	point.new(-21.5, 36),
	point.new(-41, 23),
	point.new(-50, 1.5),
	point.new(-45, -27),
	point.new(-24.5, -44.5),
	point.new(-1, -50),
}

elevator1 = levelgen:findObjectById(3)
elevator2 = levelgen:findObjectById(4)
elevator3 = levelgen:findObjectById(5)
elevatorTog = false

gravitySinkItem = levelgen:findObjectById(6)

petResourceItem = levelgen:findObjectById(8)
ownerBox = levelgen:findObjectById(9)
petResourceShip = nil ----THE CHOSEN ONE!
chosenOne = nil  --The chosen ones name.  
exclamationPoint = levelgen:findObjectById(11)
petSpeed = 15
petEnraged = false
spyEye = levelgen:findObjectById(14)  --Robbie the resource's eye

sammy = {}
sammy["following"] = nil
sammy["chasing"] = nil
sammy["id"] = 40
sammy["zone"] = 29
sammy["speed"] = 10
sammy["distanceTolerance"] = 500
sammy["stopFollowing"] = 200
sammy["zoneDist"] = 400
sammy["action"] = "wander" -- follow, wander, chase
sammy["timer"] = 0
sammy["dir"] = 0

doomsdayIsActive = false

lights1 = levelgen:findObjectById(31)
lights2 = levelgen:findObjectById(32)
lights3 = levelgen:findObjectById(33)
lights4 = levelgen:findObjectById(34)
lights5 = levelgen:findObjectById(35)
lights6 = levelgen:findObjectById(36)
lights7 = levelgen:findObjectById(37)
lights8 = levelgen:findObjectById(38)

rockTestItem = levelgen:findObjectById(15)
rockPos = rockTestItem:getPos()
superDuperDeathAsteroidOfDoom = levelgen:findObjectById(24)
snowCenter = levelgen:findObjectById(69)

whatPopcorn = nil

killCommandEnabled = false

tau = 2 * math.pi
currentHarmonicOscillationTime = 0
speedZone1 = levelgen:findObjectById(1)
speedZone1OrigStartPoint = speedZone1:getGeom()[1]
speedZone1OrigEndPoint = speedZone1:getGeom()[2]

snowAccelorator = 1.2

resRadius = 150
shieldFactor = 10

howOftenSeeker = 4000
popcornStutter = 0

allNotes = {}
noteSpawnDistance = -1000 -- will be used for how far away a note is spawned from the accept zone (negative because it appears above)
noteSpeed = 10 -- maximum note speed
difficulty = 500 -- the maximum number of miliseconds between notes

team1Score = levelgen:findObjectById(46)
team2Score = levelgen:findObjectById(47)
team3Score = levelgen:findObjectById(48)
team4Score = levelgen:findObjectById(49)
team5Score = levelgen:findObjectById(50)
team6Score = levelgen:findObjectById(51)
team7Score = levelgen:findObjectById(52)
team8Score = levelgen:findObjectById(53)
team9Score = levelgen:findObjectById(54)
scoreArray = {team1Score, team2Score, team3Score, team4Score, team5Score, team6Score, team7Score, team8Score, team9Score}
scores = {0, 0, 0, 0, 0, 0, 0, 0, 0}

spawnPt = levelgen:findObjectById(55)

gameNexus = levelgen:findObjectById(57)

launchVelx = 10000000
launchVely = 0

merryGoRoundCenter = levelgen:findObjectById(59):getPos()
merry1 = levelgen:findObjectById(60)
merry2 = levelgen:findObjectById(61)
merry3 = levelgen:findObjectById(62)
merry4 = levelgen:findObjectById(63)
merry5 = levelgen:findObjectById(64)
merry6 = levelgen:findObjectById(65)
merry7 = levelgen:findObjectById(66)
merry8 = levelgen:findObjectById(67)

orbitAng = 0
orbitRadius = 500
isInOrbit = false
sinkPull = 200 --faster slower
	
merryArray = {merry1, merry2, merry3, merry4, merry5, merry6, merry7, merry8}

bumperCars = {}
speedCoefficient = 2

santiPowerupedPlayers = {}
santiSpawn = levelgen:findObjectById(71):getPos()
beater1 = {}
beater1["type"] = ResourceItem
beater1["center"] = point.new(3187.5, -1402.5) --this one changes when I add the items.  Oops.
beater1["trueCenter"] = point.new(3187.5, -1402.5)
beater1["length"] = 8 --how many to make + 1.
beater1["objects"] = {}
beater1["orbitTime"] = 5000
beater1["x"] = 0
beater1["y"] = 50 --a resourceItem is about this big.
beater1["orbitDirection"] = -1 -- positive for counter clockwise, negative for clockwise

beaterArray = {beater1}

origin = point.zero -- The origin
  ----------------------------------------------------------------------------//Kinetic
function addGravity()
	for i, v in ipairs(playersExist)
	do
		local fast = false
		local ship = v:getShip()
		local shipVelo = ship:getVel()
		if(shipVelo.y > 500) then
			fast = true
		elseif(shipVelo.y < 500) then
			fast = false
		end
		
		if(fast ~= true) then
			ship:setVel(point.new(shipVelo.x, shipVelo.y + 60))
		end
		
	end
end
function doGravitySink()   --This method does something!  (its the testitem-X part)
	local objLoc = gravitySinkItem:getPos()
	local sinkLoc = point.new(1912, 127) --I could theoretically make this an object or player or something
	local directionVector = point.new(objLoc.x - sinkLoc.x, objLoc.y - sinkLoc.y)
	local normalizedDirectionVector = point.normalize(directionVector)
	local sinkPull = 20
	local velocityVector = point.new(normalizedDirectionVector.x * sinkPull, normalizedDirectionVector.y * sinkPull)
	local objectVelocity = gravitySinkItem:getVel()
	gravitySinkItem:setVel(point.new(objectVelocity.x - velocityVector.x, objectVelocity.y - velocityVector.y)) --for solid velocities, make sure its negative
end

function doPetResourceItem()
	local objLoc = petResourceItem:getPos()
	if(petResourceShip ~= nil) then
		local shipsLoc = petResourceShip:getPos()
		
		local directionVector = point.new(objLoc.x - shipsLoc.x, objLoc.y - shipsLoc.y)
		local normalizedDirectionVector = point.normalize(directionVector)
		local velocityVector = point.new(normalizedDirectionVector.x * petSpeed, normalizedDirectionVector.y * petSpeed)
		local objectVelocity = petResourceItem:getVel()
		petResourceItem:setVel(point.new(objectVelocity.x - velocityVector.x, objectVelocity.y - velocityVector.y))
	end
	moveSpyEye(objLoc)
end
function resetRobbie()  --if function sent from message true, else false
	if(petResourceShip == nil) then
		petSpeed = 15
		petResourceItem:setPos(point.new(2550, -637))
		petResourceItem:setVel(point.new(0,0))
		globalMsg("Robbie has been reset.")
		regenerateEye()
	elseif(petResourceShip ~= nil) then
		logprint("Cannot reset when Robbie has an owner")
	end
end
function matchRobbie()	
	local resCoords = petResourceItem:getPos()
	local upLeft = point.new(resCoords.x - 150, resCoords.y - 150)
	local botLeft = point.new(resCoords.x - 150, resCoords.y + 150)
	local upRight = point.new(resCoords.x + 150, resCoords.y - 150)
	local downRight = point.new(resCoords.x + 150, resCoords.y + 150)

	ownerBox:setGeom(upLeft, upRight, downRight, botLeft)
end
function moveSpyEye(resLoc) --Totally sneaking the exclamation point in here with it.
	spyEye:setPos(resLoc) 
	exclamationPoint:setGeom(point.new(resLoc.x + 10, resLoc.y - 100), point.new(resLoc.x - 10, resLoc.y - 100))
end
function changeExclamation()
	exclamationPoint:setTeam(-2)
end
function doSammy()
    local zone = levelgen:findObjectById(sammy["zone"])
    local speed = levelgen:findObjectById(40)
    local loc = speed:getPos()
    --sammy's movement
    if (sammy["following"] ~= nil) then
        if (sammy["action"] ~= "chase") then
            local playerLoc = sammy["following"]:getShip():getPos()
            local dist = point.distanceTo(loc, playerLoc)
            --start following?
            if (dist > sammy["distanceTolerance"]) then
                sammy["action"] = "follow"
            end
            --sop following?
            if (sammy["action"] == "follow") then
                if (dist > sammy["stopFollowing"]) then
                    local dir = point.angleTo(loc, playerLoc)
                    local newLoc = point.new(loc.x + (sammy["speed"]*math.cos(dir)), loc.y + (sammy["speed"]*math.sin(dir)))
                    speed:setGeom(newLoc, playerLoc)
                else
                    sammy["action"] = "wander"
                    sammy["timer"] = 0
                end
            end
            --wandering?
            if (sammy["action"] == "wander") then
                sammy["timer"] = sammy["timer"] + 1
                if (sammy["timer"] == 45) then
                    sammy["dir"] = math.random()*2*math.pi
                end
                if (sammy["timer"] > 45) then
                    local newLoc = point.new(loc.x + (sammy["speed"]*math.cos(sammy["dir"])), loc.y + (sammy["speed"]*math.sin(sammy["dir"])))
                    local pointLoc = point.new(loc.x + ((sammy["speed"]+1)*math.cos(sammy["dir"])), loc.y + ((sammy["speed"]+1)*math.sin(sammy["dir"])))
                    speed:setGeom(newLoc, pointLoc)
                end
                if (sammy["timer"] > 75) then
                    sammy["timer"] = 0
                end
            end
        else
            --chasing
            local playerLoc = sammy["chasing"]:getShip():getPos()
            local dir = point.angleTo(loc, playerLoc)
            local newLoc = point.new(loc.x + (sammy["speed"]*math.cos(dir)), loc.y + (sammy["speed"]*math.sin(dir)))
            speed:setGeom(newLoc, playerLoc)
            local dist = point.distanceTo(newLoc, playerLoc)
            if (dist > sammy["zoneDist"]) then
                sammy["chasing"] = nil
                sammy["action"] = "follow"
            end
        end
    end
    --sammy updates his zone
    if (sammy["following"] ~= nil) then
        loc = sammy["following"]:getShip():getPos()
    end
    local p1 = point.new(loc.x-sammy["zoneDist"], loc.y-sammy["zoneDist"])
    local p2 = point.new(loc.x-sammy["zoneDist"], loc.y+sammy["zoneDist"])
    local p3 = point.new(loc.x+sammy["zoneDist"], loc.y+sammy["zoneDist"])
    local p4 = point.new(loc.x+sammy["zoneDist"], loc.y-sammy["zoneDist"])
    zone:setGeom(p1, p2, p3, p4)
end
function regenerateEye()
	spyEye:removeFromGame()
	local spyeye = SpyBug.new()
	spyeye:setTeam(-1)		
	levelgen:addItem(spyeye)
	spyEye = spyeye
end

function generateHealthPacks()
	for i, v in pairs(registeredPlayers)
	do
		local player = v:getShip()
		local packVar = HealthItem.new()
		
		levelgen:addItem(packVar)
		moveHealthPack(player, packVar)
	end
end
function moveHealthPacks(ship, packVar)
	local playerLoc = ship:getPos()
	local shipVel = ship:getVel()
	local normalizeVel = shipVel --point.normalize(shipVel)
	packVar:setPos(point.new(shipLoc.x + normalizeVel.x, shipLoc.y + normalizeVel.y))
	moveHealthPacks(ship, packVar)  --Call the function itself again, setting up a loop specific to the item
end
function healthPackStuff() --this is the only one I actually use I *think*
	-- First go through our player registry and check if a health pack is tied to each player
	-- If not, register one to their name
	for index, value in ipairs(registeredPlayers) do 
		-- First check that the player is valid
		if value ~= nil then
			-- The 'value' here is the PlayerInfo object that is registered
			local playerName = value:getName()

			-- Check to see if the player has a health pack tied to them in the health pack registry
			if registeredHealthPacks[playerName] == nil then
				-- Create new health pack
				local healthPack = RepairItem.new()
				healthPack:setRegenTime(1)
				levelgen:addItem(healthPack)
				
				-- Now register to the player's name in our dictionary
				registeredHealthPacks[playerName] = healthPack
			end

			-- Now move the health pack to the player location
			
			-- Get pack for this player
			local pack = registeredHealthPacks[playerName]
			
			-- Get ship for this player
			local ship = value:getShip()
			-- If ship exists
			if ship ~= nil then
				local shipLoc = ship:getPos()
				local shipVel = ship:getVel()
				local normalizeVel = point.normalize(shipVel)
				pack:setGeom(point.new(shipLoc.x + normalizeVel.x, shipLoc.y + normalizeVel.y))
		--		moveHealthPacks(ship, packVar)  --Call the function itself again, setting up a loop specific to the item				
				-- set health pack location below the ship
		--		pack:setGeom(point.new(shipLoc.x, shipLoc.y))
			end
		end
	end
end

function doBeaters(deltaTime)
	for index, value in ipairs(beaterArray)
	do
		for dex, val in ipairs(value["objects"]) --orbit 
		do
			--[[ kaen:
				well, it's kind of hairy
				but if you understand vector math it's very simple
				the position is just a point on a circle at time t
				well then, we just cauclate a new destination point that will guide the ship around in a circle
				the velocity is perpendicular to (satPos - center)
				it has magnitude equal to the orbit's circumference / period --period being like, orbit time
				(because velocity * period equals circumference)
			--]]
			--[[
				centered on a coordinate axis
				and draw a right triangle like this:
				https://en.wikipedia.org/wiki/File:Unit_circle.svg
				imagine the ship is at the dot
				then increase t a little bit
				that formula I pasted above will tell you where the next x,y is
				the legnth of the diagonal line is labeled in that diagram as 1
				but in orbitbot it is orbitradius

			--]]
			local t = getMachineTime() % (value["orbitTime"]) / value["orbitTime"]
 
			local center = value["trueCenter"]
			local radius = point.distanceTo(val["loc"], center)
			
			local pos = center + point.new(math.sin((t + 1/5) * tau * value["orbitDirection"]), math.cos((t + 1/5) * tau * value["orbitDirection"])) * radius
			local unitVec = point.normalize(center - pos)
			val["item"]:setVel(point.new(value["orbitDirection"] * -unitVec.y,value["orbitDirection"] * unitVec.x) * tau * radius / (value["orbitTime"] / 1000))
			val["item"]:setPos(pos)
		end
	end
end

function changeElevator()
	if(elevatorTog == false) then
		elevatorTog = true
	elseif(elevatorTog == true) then
		elevatorTog = false
	end
end
function moveElevator()
	if(elevatorTog == false) then
		elevator1:setVel(point.new(0, -200))
		elevator2:setVel(point.new(0, -200))
		elevator3:setVel(point.new(0, -200))
	elseif(elevatorTog == true) then
		elevator1:setVel(point.new(0, 200))
		elevator2:setVel(point.new(0, 200))
		elevator3:setVel(point.new(0, 200))
	end
end
function doPopcorn()
	if(whatPopcorn ~= nil) then
		local loc = point.new(2601, 1530)
		local yvel = math.random(400)
		local xvel = math.random(200) - 100
		spawnvar = whatPopcorn.new()
		spawnvar:setPos(loc)
		if(whatPopcorn == Asteroid) then
			spawnvar:setSize(1)
		elseif(whatPopcorn == Burst) then
			yvel = math.random(1500)
		elseif(whatPopcorn == SoccerBallItem) then
			yvel = math.random(600)
		
		end
		if(whatPopcorn ~= SpyBug) then
			spawnvar:setVel(point.new(xvel, 0 - yvel))  ---- xvel, yvel.  A negative y vel is upwards.
			levelgen:addItem(spawnvar)
			removeObjectFromGameWithDelay(spawnvar, math.random(4000))
		else
			if(popcornStutter < 1) then
				spawnvar:setVel(point.new(xvel, 0 - yvel))  ---- xvel, yvel.  A negative y vel is upwards.
				levelgen:addItem(spawnvar)
				removeObjectFromGameWithDelay(spawnvar, math.random(4000))
				popcornStutter = 15

			end
			popcornStutter = popcornStutter - 1
		end
	end
end
function doMerryGoRound(deltaTime)
	for index, item in ipairs(merryArray)
	do
		local vel = item:getVel()
		local loc = item:getPos()
		local origin = merryGoRoundCenter --copied from candyland, where it orbits around center. 

		local distSq = point.distSquared(loc, origin)

		-- Here we use the deltaTime to make the motion look smooth.
		-- If we just advanced orbitAng by a fixed amount each frame, it would
		-- appear jerky, as each frame is a slightly different length.

		-- .0015 determined experimentally
		orbitAng = orbitAng + .0015 * deltaTime


		local dest
		dest = origin
		if( distSq <= orbitRadius * orbitRadius * 1.1 ) then    -- Close enough to enter orbit
			if( not isInOrbit ) then
				orbitAng = point.angleTo( loc, dest ) - math.pi / 2
			end    

			isInOrbit = true

		else                                    -- Travel directly toward origin
			orbitAng = point.angleTo( loc, dest )
			isInOrbit = false
		end

		local directionVector = dest - loc

		if(isInOrbit) then
			directionVector = point.new(-directionVector.y, directionVector.x)
		end

		local normalizedDirectionVector = point.normalize(directionVector)
	
		local velocityVector = point.new(normalizedDirectionVector.x * sinkPull, normalizedDirectionVector.y * sinkPull)
		-- local objectVelocity = item:getVel()
		-- item:setVel(point.new(objectVelocity.x - velocityVector.x, objectVelocity.y - velocityVector.y)) --for solid velocities, make sure its negative
		item:setVel(velocityVector) -- "if you adjust towards velocity vector instead of setting to it immediately, it should respond to nudges

		--   item:setVel( dest )                         -- Travel towards calculated point
	end
end
function doBumperCars()
	for index, info in ipairs(bumperCars)
	do
		local ship = info:getShip()
		if(ship ~= nil) then
			local angle = ship:getAngle()
			local vel = ship:getVel()
			local normalizedVel = point.normalize(vel)
			local newVel = point.new(normalizedVel.x * 450 * speedCoefficient, normalizedVel.y * 450 * speedCoefficient)
			ship:setVel(newVel)
		end
	end
end
function doSantiPowerups()
	for index, info in ipairs(santiPowerupedPlayers)
	do
		local ship = info:getShip()
		if(ship ~= nil) then
			if(ship:isModActive(Module.Shield)) then
				angle = ship:getAngle()
				shipPos = ship:getPos()
				local newX = -200*math.cos(angle)
				local newY = -200*math.sin(angle)
				bursts(point.new(shipPos.x + newX, shipPos.y + newY))
			end
		end
	end
end
function harmonicOscillator(deltaTime, totalTime)
	if currentHarmonicOscillationTime + deltaTime >= totalTime then
		currentHarmonicOscillationTime = 0
	else
		currentHarmonicOscillationTime = currentHarmonicOscillationTime + deltaTime
	end
	
	return math.sin(tau * (currentHarmonicOscillationTime / totalTime))
end
function slide1(deltaTime, totalSlideTime, totalSlideDistance)	
	local oscillator = harmonicOscillator(deltaTime, totalSlideTime)
	
	-- This is the distance from the original starting location
	local slideDistance = oscillator * totalSlideDistance * 3
	
	local newStartPoint = point.new(speedZone1OrigStartPoint.x, speedZone1OrigStartPoint.y + slideDistance)
	local newEndPoint = point.new(speedZone1OrigEndPoint.x, speedZone1OrigEndPoint.y  + slideDistance)
	
	speedZone1:setGeom(newStartPoint, newEndPoint)
end
                      ----------------------------------------------------------//Explodies
function registerShip(ship)
	local info = ship:getPlayerInfo()

	alreadyRegistired = false
	for index, value in ipairs(registeredPlayers)
	do
		if(value == info) then
			alreadyRegistired = true
			break
		end
	end
	
	local playerName = info:getName()
	-- If not already registered, register!
	if alreadyRegistired == false then
		logprint("registering "..playerName)
		table.insert(registeredPlayers, info)
	end
end
--------------------------------------------//Swords
function rotateAboutPoint(inputPoint, rotationPoint, angle)
	-- Trig!
	local cosAngle = math.cos(angle)
	local sinAngle = math.sin(angle)

    local x = rotationPoint.x + (((inputPoint.x-rotationPoint.x)*cosAngle) - ((inputPoint.y-rotationPoint.y)*sinAngle))
    local y = rotationPoint.y + (((inputPoint.x-rotationPoint.x)*sinAngle) + ((inputPoint.y-rotationPoint.y)*cosAngle))
    
    return point.new(x, y);
end
function translateObjectGeom(inputGeom, startPoint, angle)
	local outputGeom = {}
	
	-- Our rotatePoint will always be the first in the input geometry
	local rotatePoint = inputGeom[1]
	
	for index, value in ipairs(inputGeom) do
		-- Our first point we don't need to do translation/rotation
		if index == 1 then
			table.insert(outputGeom, point.new(startPoint.x + rotatePoint.x, startPoint.y + rotatePoint.y))
		else
			local newPoint = rotateAboutPoint(value, rotatePoint, angle)
			table.insert(outputGeom, point.new(startPoint.x + newPoint.x, startPoint.y + newPoint.y))
		end
	end
	
	return outputGeom
end
function zoneSwords()
	-- First go through our player registry and check if a sword is tied to each player
	-- If not, register one to their name
	for index, value in ipairs(playersInSwords) do 
		-- First check that the player is valid
		if value ~= nil then
			-- The 'value' here is the PlayerInfo object that is registered
			local playerName = value:getName()
			local playerTeam = value:getTeamIndex()
		
			-- Check to see if the player has a sword tied to them in the sword registry
			if registeredZoneSwords[playerName] == nil then
				-- Create new sword
				local swordZone = GoalZone.new()
				swordZone:setGeom(basicSwordGeom)
				levelgen:addItem(swordZone)
				
				-- Now register to the player's name in our dictionary
				registeredZoneSwords[playerName] = swordZone
			end

			-- Get sword for this player
			local sword = registeredZoneSwords[playerName]
			
			-- Get ship for this player
			local ship = value:getShip()
			-- If ship exists
			if ship ~= nil then
				local shipLoc = ship:getPos()
				
				-- Move our sword.  Note that the input is our basic geometry (NOT current geometry)
				local newGeom = translateObjectGeom(basicSwordGeom, shipLoc, ship:getAngle())
				sword:setGeom(newGeom)
				sword:setTeam(playerTeam)
			end
		end
	end
end
---------------------------------------------//other explodies
function bursts(sacrificeloc)
	boom = Burst.new()
	boom:setPos(point.new(sacrificeloc.x, sacrificeloc.y))
	levelgen:addItem(boom)
end
function spawnMines(loc)
	spawnvar = Mine.new()
	spawnvar:setPos(loc)
	levelgen:addItem(spawnvar)
end
function fireSeeker()
	seekVar = Seeker.new()
	seekVar:setVel(point.new(math.random(5000), math.random(50) - 25))
	seekVar:setPos(point.new(-4539, 1326))
	levelgen:addItem(seekVar)
	Timer:scheduleOnce(fireSeeker, howOftenSeeker)
end
function superAsteroid()
	if(superDuperDeathAsteroidOfDoom ~= nil) then
		superDuperDeathAsteroidOfDoom:setSize(3)
		local vel = superDuperDeathAsteroidOfDoom:getVel()
		local angle = math.random() * tau
		superDuperDeathAsteroidOfDoom:setVel(point.new(vel.x + 50 * math.cos(angle), vel.y + 50 * math.sin(angle)))
	end
	
end
function killShip(ship, playerName)
	local location = ship:getPos()
	bursts(location)
	bursts(location)
	bursts(location) 
	bursts(location)
	bursts(location)  --4 to kill armor, and an extra just in case.
	globalMsg(playerName.." has been selected for sacrifice!")
end
function determineVictim()
	-- No players registered?  Bail!
	if #registeredPlayers == 0 then
		return
	end
	
	-- Choose a random index from the registeredPlayers table, from 1 to the length of the
	-- table.  Note  '#' next to a table means get table length
	local randomIndex = math.random(1, #registeredPlayers)
	local playerInfo = registeredPlayers[randomIndex]
	
	-- playerInfo could disappear if the player disconnects from server.  De-register
	-- and try again later
	if playerInfo == nil then
		logprint("Where did the player go?  Waiting until next round")
		table.remove(registeredPlayers, randomIndex)
		return
	end
	
	local ship = playerInfo:getShip()
	local playerName = playerInfo:getName()
	
	-- Ship can disappear between dying and spawning.  Let's do a check here
	if ship == nil then
		return
	end
	
	killShip(ship, playerName)
end
                     -------------------------------------------------------//Not sure what's down here yet.  Misc
function changeLights()
	local randomVar = math.random(9)
	lights1:setTeam(randomVar)
	randomVar = math.random(9)
	lights2:setTeam(randomVar)
	randomVar = math.random(9)
	lights3:setTeam(randomVar)
	randomVar = math.random(9)
	lights4:setTeam(randomVar)
	randomVar = math.random(9)
	lights5:setTeam(randomVar)
	randomVar = math.random(9)
	lights6:setTeam(randomVar)
	randomVar = math.random(9)
	lights7:setTeam(randomVar)
	randomVar = math.random(9)
	lights8:setTeam(randomVar)
end
function stopRock()
	local currentVel = rockTestItem:getVel()
	rockTestItem:setVel(point.new(0,0))
	rockTestItem:setPos(rockPos)
end
function moveNexus()
	nexusGeom = gameNexus:getGeom()
	local newGeom = {}
	for index, pointVal in ipairs(nexusGeom)
	do
		local randomX = math.random(11) - 6       --11 - 6 = -5 to 5
		local randomY = math.random(11) - 6
		
		newPoint = point.new(pointVal.x + randomX, pointVal.y + randomY)
		table.insert(newGeom, newPoint)
	end
	gameNexus:setGeom(newGeom)
end
function doSnow(deltatime)
	--for index, object in ipairs(snowRes) do
	--	object:setVel(point.new(math.random(500) - 250, math.random(500) - 250))
  --  end
	for index, object in ipairs(snowRes) do
		vel = object:getVel()
		pos = object:getPos()
		centerPos = snowCenter:getPos()
		local pox = centerPos.x - pos.x
		local poy = centerPos.y - pos.y
		a = math.atan2(pox, poy)
		object:setVel(point.new(vel.x - math.cos(a) * snowAccelorator * deltatime, vel.y + math.sin(a) * snowAccelorator * deltatime))
    end
end
function moveCotton(ship, item)
	if(ship:getPos() ~=nil)then
		if(item:getPos() ~= nil) then
			local shipLoc = ship:getPos()
			local itemLoc = item:getPos()
			local newGeom = translateObjectGeom(cottonCandyGeom, shipLoc, ship:getAngle())
			item:setGeom(newGeom)
			Timer:scheduleOnce(function () moveCotton(ship, item) end, 50)
			removeObjectFromGameWithDelay(item, 10000)
		end
	end
end
function doCottonCandy(ship)
	spawnVar = GoalZone.new()
	spawnVar:setGeom(cottonCandyGeom)
	spawnVar:setTeam(5)
	levelgen:addItem(spawnVar)
	moveCotton(ship, spawnVar)
end
function doShield(ship, item)
	if(ship:getPos() ~=nil)then
		if(item:getPos() ~= nil) then
			local shipLoc = ship:getPos()
			local itemLoc = item:getPos()
			if(itemLoc.x < 1275 and itemLoc.x > 765) then
				if(itemLoc.y < -2040 and itemLoc.y > -2550) then
					removeObjectFromGameWithDelay(item, 1000)
				else
					local angle = math.random() * tau
					item:setPos(point.new(shipLoc.x + resRadius * math.cos(angle), shipLoc.y + resRadius * math.sin(angle)))
					item:setVel(point.new(0,0))
					Timer:scheduleOnce(function () doShield(ship, item) end, 50)
				end
			else
				local angle = math.random() * tau
				item:setPos(point.new(shipLoc.x + resRadius * math.cos(angle), shipLoc.y + resRadius * math.sin(angle)))
				item:setVel(point.new(0,0))
				Timer:scheduleOnce(function () doShield(ship, item) end, 50)
			end
		end
	else
		removeObjectFromGameWithDelay(item, 10000)
	end
end
function makeShield(ship)
	for i = 1, shieldFactor do 
		local item = ResourceItem.new()  
		local shipLoc = ship:getPos()
        item:setPos(point.new(shipLoc.x + math.random(20) - 10, shipLoc.y + math.random(20) - 10))
        levelgen:addItem(item)
        i=i+1
		doShield(ship, item)
	end
end
function copyToArray(input)
	local array = { }
	for index, value in pairs(input) do
		if value ~= nil then
			table.insert(array, value)
		end
	end
	return array
end

function generateClockPoints(center, pointCount, radius)
	local theta = math.tau / pointCount
	local startAngle = (math.tau / 2) + theta  -- top of the circle + one angle; kinda weird, i know
	
	-- Used as dictionary
	local d = {}
	
	local x, y
	for i = 1, pointCount do
		x = radius * math.sin(startAngle - (i * theta))
		y = radius * math.cos(startAngle - (i * theta))
		
		d[i] = point.new(x, y)
	end
		
	return d
end
function adjustClockZone()
	clockPointCount = dsize(pointArray)
  
	-- We've shrunk all the way, time to increase
	if clockPointCount == 1 and decrease == true then
		decrease = false
	end
	
	-- We're as big as we can get, time to shrink
	if clockPointCount == numPoints and decrease == false then
		decrease = true
	end
	
	-- If we're on count 1 that means we have only 1 point left in the zone, or it is full,
	-- so skip adjustments
	if ringCounter ~= 1 then
		-- Now adjust geom, need to do this using pointArray as a dictionary
		if decrease == true then
			-- If removing, remove the last point in the table
			pointArray[ringCounter] = nil
		else
			-- If adding, add to the table in reverse winding order
			pointArray[ringCounter] = cachedPointArray[ringCounter]
		end
		
		-- Convert to array for setting Geom
		clockZone:setGeom(copyToArray(pointArray))
	end
	
	-- Update ring counter
	ringCounter = ringCounter + 1
	
	-- Adjust our counter, this is essentially the zone point index to adjust
	if ringCounter > numPoints then
		ringCounter = 1
	end
end

function spawnObject(object, ship, team)
	if(ship ~= nil) then
		local shipLoc = ship:getPos()
		local shipHealth = ship:getHealth()
		local angle = ship:getAngle()
		local newX = 0
		local newY = 0
		if(angle ~= nil) then
			local newX = 200*math.cos(angle)
			local newY = 200*math.sin(angle)
		else
			local newX = 0
			local newY = 0
		end
		spawnVar = object.new()
		spawnVar:setTeam(team)
		spawnVar:setPos(point.new(shipLoc.x + newX, shipLoc.y + newY))
		if(object == Asteroid) then
			spawnVar:setVel(point.new(0,0)) --Or else asteroids will instakill you when you make them
		elseif(object == CoreItem) then
			spawnVar:setFullHealth(shipHealth * 10) --max core health is determined by how strong your ship is.
		end
		levelgen:addItem(spawnVar)
		return spawnVar
	end
end
--------------------------------------------------------//DDR stuff
function dance()
	if (true) then -- replace true with what you want to be making sure DDR is running

		local danceNote = {}
		danceNote["direction"] = math.random(4) -- assigning a random number 1-4
		danceNote["accept"] = levelgen:findObjectById(danceNote["direction"]+41) -- Math. Will get zone with id's 42-45 to match direction
		danceNote["speed"] = math.random(noteSpeed)
		danceNote["zone"] = GoalZone.new()
		
		danceNote["zone"]:setTeam(math.random(9)) -- you will want to make this the number of teams you want to play
		local points = {}
		local geom = danceNote["accept"]:getGeom()
		for i=1,4 do
			points[i] = point.new(geom[i].x, geom[i].y + noteSpawnDistance)
		end
		danceNote["zone"]:setGeom(points[1],points[2],points[3],points[4])
		levelgen:addItem(danceNote["zone"])
		table.insert(allNotes, danceNote)
	end
	Timer:scheduleOnce(dance, math.random(difficulty))
end
function noteStep(ship, zone)
	if (zone:getTeamIndex() == ship:getTeamIndex()) then
		local newAllNotes = {}
		for k,v in ipairs(allNotes) do
			if(zone:getId() == v["zone"]:getId()) then
				local dist = point.distanceTo(v["zone"]:getGeom()[1], v["accept"]:getGeom()[1])
				-- player stepped on a note. dist is the distance to the button
				local zoneObj = v["zone"]
				removeObjectFromGameWithDelay(zoneObj, 100)
				calculateScore(ship, dist)
				v = nil
			else
				table.insert(newAllNotes, v)
			end
		end
		allNotes = newAllNotes
	end
end
function moveNotes()
	local newAllNotes = {}
	for k,v in ipairs(allNotes) do
		if (v["zone"] ~= nil) then
			local geom = v["zone"]:getGeom()
			local points = {}
			for i=1,4 do
				points[i] = point.new(geom[i].x, geom[i].y + v["speed"])
			end
			v["zone"]:setGeom(points[1],points[2],points[3],points[4])
			
			if (geom[1].y > v["accept"]:getGeom()[1].y) then
				--this is where a player missed a note.
				--If you want to have text for that, put it here
				local zoneObj = v["zone"]
				removeObjectFromGameWithDelay(zoneObj, 100)
				v = nil
			else
				table.insert(newAllNotes, v)
			end
		end
	end
	allNotes = newAllNotes
end
function calculateScore(ship, dist)
	local playerTeam = ship:getTeamIndex()
	local scoreValue = 0 ---will change depending on how accurate they hit it
	
	if(dist > 255) then
		textNearShip(ship, "  BOO!"  , -1)
		scoreValue = 0
	elseif(dist > 100) then
		textNearShip(ship, "  meh.  ", -1)
		scoreValue = 10
	elseif(dist > 75) then
		textNearShip(ship, "  good  ", -1)
		scoreValue = 25
	elseif(dist > 50) then
		textNearShip(ship, "  Great!  ", -1)
		scoreValue = 75
	elseif(dist > 25) then
		textNearShip(ship, "  Awesome!  ", -1)
		scoreValue = 100
	elseif(dist > 0) then
		textNearShip(ship, "  Perfect!  ", -1)
		scoreValue = 250
	end
	for index, scoreboard in ipairs(scoreArray)
	do
		if(index == playerTeam) then
			scores[index] = scores[index] + scoreValue
		end
	end
end
function showScore()
	for index, scoreboard in ipairs(scoreArray)
	do
		if(scores[index] ~= 0) then
			scoreboard:setText(tostring(scores[index]))
			scoreboard:setGeom(scoreboard:getGeom())
		end
	end
end
----------------------------------------------------------------------
function textNearShip(ship, textMsg, team)
	local loc = ship:getPos()
	textitem = TextItem.new()
	textitem:setText(textMsg)
	textitem:setTeam(team)
	
	local textGeom = {
	point.new(loc.x - 150, loc.y + 25),
	point.new(loc.x + 150, loc.y + 25)
	}
	textitem:setGeom(textGeom)

	levelgen:addItem(textitem)
	removeObjectFromGameWithDelay(textitem, 1000)
end

function removeObjectFromGameWithDelay(object, delay)
	if object ~= nil then
		Timer:scheduleOnce(function() object:removeFromGame() end, delay)
	end
end
 -------------------------------------------------------------------------//Tables
function removeFromDictionary(dictionary, key)
	dictionary[key] = nil
end
function dsize(dictionary)
	local counter = 0
	for k, v in pairs(dictionary) do
		if v ~= nil then
			counter = counter + 1
		end
	end
	return counter
end
function searchAndRemoveFromTable(someTable, valueObject)
	local localIndexToRemove = -1
	for i, v in ipairs(someTable)
	do
		if(v == valueObject) then
			localIndexToRemove = i
			break
		end
	end

	if localIndexToRemove ~= -1 then
		table.remove(someTable, localIndexToRemove)
		
	end
end
function insertIntoTableIfUnique(someTable, valueObject)
	local foundObject = false
	for i, v in ipairs(someTable)
	do
		if(v == valueObject) then
			foundObject = true
			break
		end
	end

	if foundObject == false then
		table.insert(someTable, valueObject)
	end
end
                     ------------------------------------------------------//Subscribed functions
function onShipEnteredZone(ship, zone, zoneType, zoneId)
	local info = ship:getPlayerInfo()
	local name = info:getName()
	local playerTeam = info:getTeamIndex()
	local thisZone = registeredZoneSwords[name]
	local zoneteam = zone:getTeamIndex()
	local isSword = false
	
	local zoneGeom = zone:getGeom()
	local pointCount = #zoneGeom
	
	noteStep(ship, zone)
	
	if pointCount == 10 then
		isSword = true
	end
	
	if(isSword == true) then
		if(zone:getTeamIndex() ~= playerTeam) then
			local loc = ship:getPos()
			boom = Burst.new()
			boom:setPos(point.new(loc.x, loc.y))
			boom:setTeam(zone:getTeamIndex())
			levelgen:addItem(boom)
		end
	end
	
	if(zoneId == 7) then
		local zoneLoc = zone:getPos()
		local mineSpawnPoint1 = point.new(zoneLoc.x + 100, zoneLoc.y) -- right
		local mineSpawnPoint2 = point.new(zoneLoc.x - 100, zoneLoc.y) -- left
		local mineSpawnPoint3 = point.new(zoneLoc.x, zoneLoc.y + 100) -- down
		local mineSpawnPoint4 = point.new(zoneLoc.x, zoneLoc.y - 100) -- up
		spawnMines(mineSpawnPoint1)
		spawnMines(mineSpawnPoint2)
		spawnMines(mineSpawnPoint3)
		spawnMines(mineSpawnPoint4)
		
	elseif(zoneId == 9) then
		if(petResourceShip == nil) then
			local info = ship:getPlayerInfo()
			petResourceShip = ship
			local shipsTeam = petResourceShip:getTeamIndex()
			chosenOne = info:getName()
			exclamationPoint:setTeam(shipsTeam)
			globalMsg("Robbie has accepted "..chosenOne.." as his new owner! Please be nice to them!")
			Timer:scheduleOnce(changeExclamation, 5000)
		end
		
	elseif(zoneId == 10) then
		table.insert(playersExist, ship:getPlayerInfo())
		
	elseif(zoneId == 12) then
		if(petEnraged == false) then
			if(petResourceShip ~= nil) then
				petSpeed = 9001 
				petEnraged = true
				globalMsg("Robbie is enraged!")
			end
		elseif(petEnraged == true) then
			if(petResourceShip ~= nil) then
				petSpeed = 20
				petEnraged = false
				globalMsg("Robbie has calmed down.")
			end
		end
		
	elseif(zoneId == 13) then
		if(doomsdayIsActive == false) then	
			local info = ship:getPlayerInfo()
			culprit = info:getName()
			Timer:scheduleRepeating(determineVictim, 30000)
			globalMsg(culprit.." has powerd up the Doomsday Device!")
			globalMsg("To prevent armaggedon, we will periodically be sacrificing a random player.")
			globalMsg("Thank you for your patience.")
			doomsdayIsActive = true
		end
	elseif(zoneId == 16) then 
		insertIntoTableIfUnique(playersInSwords, ship:getPlayerInfo())
	elseif(zoneId == 17) then 
		whatPopcorn = ResourceItem
	elseif(zoneId == 18) then 
		whatPopcorn = TestItem
	elseif(zoneId == 19) then 
		whatPopcorn = Asteroid	
	elseif(zoneId == 20) then 
		whatPopcorn = SoccerBallItem	
	elseif(zoneId == 21) then 
		whatPopcorn = Seeker
	elseif(zoneId == 22) then 
		whatPopcorn = Burst
		if(math.random(10) == 1) then
			whatPopcorn = Mine
		end
	elseif(zoneId == 23) then 
		whatPopcorn = SpyBug
	elseif(zoneId == 30) then
		changeLights()
	elseif(zoneId == 39) then
		makeShield(ship)
	elseif(zoneId == 25) then
		doCottonCandy(ship)
	elseif(zoneId == 26) then
		howOftenSeeker = 5000
	elseif(zoneId == 27) then
		howOftenSeeker = 4000
	elseif(zoneId == 28) then
		howOftenSeeker = 2000
	elseif (zoneId == sammy["zone"] and ship:getPlayerInfo() ~= sammy["following"]) then
        if (sammy["following"] == nil) then
            sammy["following"] = ship:getPlayerInfo()
            sammy["action"] = "wander"
            sammy["timer"] = 0
			globalMsg("Sammy has accepted "..name.." as his new owner!")
        else
            sammy["chasing"] = ship:getPlayerInfo()
            sammy["action"] = "chase"
        end
	elseif(zoneId == 2) then
		local chance = math.random(5)
		if(chance == 1) then
			ship:setVel(point.new(-2000, 0))
			textNearShip(ship, "   LOL   ", -1)
		end
	elseif(zoneId == 41) then
		---  Put team into the array.  
	elseif(zoneId == 56) then
		textNearShip(ship, "Prepare for launch!", playerTeam)
		Timer:scheduleOnce(function () 
			ship:setVel(point.new(launchVelx, launchVely)) 
		end, 2000)
		Timer:scheduleOnce(function () 
			ship:setVel(point.new(0,0))
			local a = spawnObject(Asteroid, ship, playerTeam)
			local b = spawnObject(TestItem, ship, playerTeam)
			local c = spawnObject(ResourceItem, ship, playerTeam)
			local d = spawnObject(SoccerBallItem, ship, playerTeam)
			local e = spawnObject(CoreItem, ship, playerTeam)
			Timer:scheduleOnce(function () 
				a:removeFromGame()
				b:removeFromGame()
				c:removeFromGame()
				d:removeFromGame()
				e:removeFromGame()
			end, 10000)
		end, 10000)
	elseif(zoneId == 58) then	
		ship:setVel(point.new(0, 10000))
	elseif(zoneId == 68) then
		insertIntoTableIfUnique(bumperCars, info)
	elseif(zoneId == 70) then 
		insertIntoTableIfUnique(santiPowerupedPlayers, info)
	elseif(zoneId == 101) then
		ship:setHealth(0)
	end
	
end
function onShipLeftZone(ship, zone, zoneType, zoneId) --to make it so the gravity effects can't stack
	local info = ship:getPlayerInfo()
	local name = info:getName()
	
	if(zoneId == 10) then
		for i, v in ipairs(playersExist)
		do
			if(v == ship:getPlayerInfo()) then
				table.remove(playersExist, i)
				break
			end
		end
	elseif(zoneId == 16) then
		local sword = registeredZoneSwords[name]
		removeFromDictionary(registeredZoneSwords, name)
		removeObjectFromGameWithDelay(sword, 500)
		searchAndRemoveFromTable(playersInSwords, ship:getPlayerInfo())
	elseif(zoneId == 68) then
		searchAndRemoveFromTable(bumperCars, info)
	
	end
end
function onShipKilled(ship)
	local info = ship:getPlayerInfo()
	local killedShipName = info:getName()
	if(chosenOne == killedShipName) then
		if(petResourceShip ~= nil) then
			petResourceShip = nil
			globalMsg("Robbie's owner has died.")
			exclamationPoint:setTeam(-2)
			Timer:scheduleOnce(resetRobbie, 10000)
		end
	end
	if (info == sammy["following"]) then
        sammy["following"] = sammy["chasing"]
        sammy["action"] = "wander"
		globalMsg("Sammy's owner has died")
    elseif (info == sammy["chasing"]) then
        sammy["chasing"] = nil
        sammy["action"] = "wander"
    end
	searchAndRemoveFromTable(bumperCars, info)
end
--[[            Raptors number arg parser thing
function onMsgReceived(message)
	-- This grabs a substring that matches a number, then converts it from a string
	-- to a number
	local firstParsedNumberString = string.match(message, "(%d+)")
	
	local parsedNumber = nil
	if firstParsedNumberString ~= nil then
		parsedNumber = string.format("%d", firstParsedNumberString)
	end
	
	if parsedNumber ~= nil then
		logprint(parsedNumber)
	end
end
                       Kaen's arg parser thing
function getArgs(str)
  local t = {}
  local function helper(word) table.insert(t, word) return "" end
  if not str:gsub("%w+", helper):find"%S" then return t end
end
--]]
function getArgs(inputString)
	local words = {}
	for word in inputString:gmatch("[^|]+") do --on a pipe.  I think.  %S+
		table.insert(words, word) 
	end
	return words
end
function onMsgReceived(message, playerInfo)
	name = playerInfo:getName()
	ship = playerInfo:getShip()
	if(ship ~= nil) then
		shipLoc = ship:getPos()
	end
	-----------------------------------------------------Begin raptor's parsing code
	local arguments = getArgs(message)
	-- Our 'command' is probably the first word/argument
	local command = arguments[1]
	-- Arguments are words that follow
	
	local arg1 = arguments[2]
	local arg2 = arguments[3]
	
	-----------------------------------------------------end of raptors parsing code
	if(command == "kill") then
		if(killCommandEnabled == true) then
			for index, value in pairs(registeredPlayers)
			do
				local valName = value:getName()
				local modName = string.lower(valName)
				local modArg = string.lower(arg1)
				--local namString = tostring(valName)
				if(modArg == modName) then
					local ship = value:getShip()
					local location = ship:getPos()
					bursts(location)
					bursts(location)
					logprint(name .. " killed " .. arg1)
				elseif(modArg == "robbie") then
					local location = petResourceItem:getPos()
					bursts(location)
					bursts(location)
					globalMsg(name .. " Tried to kill " .. arg1 .. "! Noooooooo")
				end
			end
		end
	end
	if(command == "hit") then
		if(killCommandEnabled == true) then
			for index, value in pairs(registeredPlayers)
			do
				local valName = value:getName()
				local modName = string.lower(valName)
				local modArg = string.lower(arg1)
				if(modArg == modName) then
					local ship = value:getShip()
					ship:setVel(point.new(math.random(25000) - 12000, math.random(25000) - 12000))
					logprint(name .. " hit " .. arg1)
				elseif(modArg == "Robbie") then
					petResourceItem:setVel(point.new(math.random(25000) - 12000, math.random(25000) - 12000))
				end
			end
		end
	end
	if(command == "snow") then
		var = tonumber(arg1)
		if(var ~= nil) then
			snowAccelorator = var
		end
	end
	if(command == "merrySpeed") then
		var = tonumber(arg1)
		if(var ~= nil) then
			sinkPull = var
		end
	end
	if(command == "launchVelx") then
		var = tonumber(arg1)
		if(var ~= nil) then
			launchVelx = var
		end
	end
	if(command == "launchVely") then
		var = tonumber(arg1)
		if(var ~= nil) then
			launchVely = var
		end
	end
	if(command == "resShield") then
		var = tonumber(arg1)
		if(var ~= nil) then
			shieldFactor = var
		end
	end
	if(command == "resRadius") then
		var = tonumber(arg1)
		if(var ~= nil) then
			resRadius = var
		end
	end
	if(command == "bumperCars") then
		var = tonumber(arg1)
		if(var ~= nil) then
			speedCoefficient = var
		end
	end
	if(message == "shh") then
		petSpeed = 5
		
	elseif(message == "Robbie come back!") then
		petResourceItem:setPos(point.new(1912, 127))
	
	elseif(message == "Robbie come back!") then
		petResourceItem:setPos(point.new(1912, 127))
	
	elseif(message == "Caffeine!") then
		petSpeed = 40
	
	elseif(message == "allow") then
		killCommandEnabled = true
		logprint(name .. " enabled attacking")
		
	elseif(message == "disallow") then
		killCommandEnabled = false
		logprint(name .. "disabled attacking")
		
	elseif(message == "nuclear") then
		petSpeed = 90000000
	
	elseif(message == "stop") then
		ship:setVel(point.new(0,0))
	
	elseif(message == "normalize") then
		petSpeed = 15
		globalMsg("Robbie has calmed down.")
	
	elseif(message == "reset") then
		resetRobbie()	
	elseif(message == "Validate me") then
		local roll = math.random(9)
		if(roll == 1) then
	
		globalMsg(name .. " is the coolest player ever!")
		
		elseif(roll == 2) then
			globalMsg("I love " .. name .. "!")
		
		elseif(roll == 3) then
			globalMsg(name .. " is an amazing bitfighter!")
		
		elseif(roll == 4) then
			globalMsg(name .. name .. name .. name .. name .. name .. "!")
		
		elseif(roll == 5) then
			globalMsg(name .. " is soooo awesome!")
		
		elseif(roll == 6) then
			globalMsg("No.")
		
		elseif(roll == 7) then
			globalMsg(name .. " is great to be around!")
		
		elseif(roll == 8) then
			globalMsg("I wish I was as smart as " .. name .. "!")
		
		elseif(roll == 9) then
			globalMsg("Honestly, " .. name .. " is a bit odd, but I like them anyway!")
		end
	
	elseif(message == "doomsday") then
		Timer:scheduleRepeating(determineVictim, 30000)
		globalMsg("Doomsday has been started!  (again) (more) (2012)")
	
	elseif(message == "eyespy") then
		regenerateEye()
	
	elseif(message == "hitme") then
		ship:setVel(point.new(math.random(25000) - 12000, math.random(25000) - 12000))
	
	elseif(message == "feed") then
		local oldLoc = petResourceItem:getPos()
		petResourceItem:removeFromGame()
		local spawnPetVar = TestItem.new()	
		spawnPetVar:setPos(oldLoc)
		levelgen:addItem(spawnPetVar)
		petResourceItem = spawnPetVar
	
	elseif(message == "unfeed") then
		local oldLoc = petResourceItem:getPos()	
		petResourceItem:removeFromGame()
		local spawnPetVar = ResourceItem.new()	
		spawnPetVar:setPos(oldLoc)
		levelgen:addItem(spawnPetVar)
		petResourceItem = spawnPetVar
		
	elseif(message == "Where's Robbie?") then
		local loc = petResourceItem:getPos()
		globalMsg("x = " .. loc.x)
		globalMsg("y = " .. loc.y)
		
	elseif(message == "setSpawn") then
		spawnPt:setPos(shipLoc)
		
	elseif(message == "status") then
		
		logprint("petspeed: " .. petSpeed)
		if(petResourceShip ~= nil) then
			local robbieInfo = petResourceShip:getPlayerInfo()
			logprint("Robbie Owner: " .. robbieInfo:getName())
		end
		logprint("Doomsday Is Active: " .. tostring(doomsdayIsActive))
		logprint("petEnraged: " .. tostring(petEnraged))
		logprint("Kill command enabled: " .. tostring(killCommandEnabled))
		logprint("snow acceleration Coefficient: " .. snowAccelorator)
		logprint("amout of resources per shield: " .. shieldFactor)
		
	elseif(message == "commands" or message == "!commands" or message == "Commands" or message == "!Commands") then
		logprint("kill [player]")
		logprint("hit [player]")
		logprint("snow [arg]")
		logprint("resShield [arg]")
		logprint("resRadius [arg]")
		logprint("merrySpeed [arg]")
		logprint("launchVelx [arg]")
		logprint("launchVely [arg]")
		logprint("shh")
		logprint("reset")
		logprint("Caffeine!")
		logprint("allow")	
		logprint("disallow")	
		logprint("nuclear")	
		logprint("stop")
		logprint("normalize")
		logprint("Validate me")
		logprint("doomsday")
		logprint("eyespy")
		logprint("hitme")
		logprint("feed")
		logprint("unfeed")
		logprint("status")
		logprint("commands")
		logprint("Where's Robbie?")
		logprint("setSpawn")
	end
end
function onShipSpawned(ship)
	insertIntoTableIfUnique(registeredPlayers, ship:getPlayerInfo())
	if(ship:getPlayerInfo():getName() == "Santiago Zap!") then
		ship:setPos(santiSpawn)
	end
end
function onPlayerLeft(playerInfo)
	searchAndRemoveFromTable(registeredPlayers, playerInfo)
	searchAndRemoveFromTable(registeredHealthPacks, playerInfo)
	logprint("deregistering " .. playerInfo:getName())
end
function onTick(deltaTime)
	
	rand = math.random(4) - 2
	if(testObj ~= nil) then
		--logprint("adjusting")
		testObj:setHealRate(0)
		--testObj:setAimAngle(rand)
		testObj:setEngineered(true)	
		--testObj:setHealth(rand)
		pos = testObj:getPos()
		testObj:setPos(point.new(pos.x + rand*2, pos.y + rand*2))
	end
	stopRock()
	healthPackStuff()
	matchRobbie()
	zoneSwords()
	doPopcorn()
	superAsteroid()
	slide1(deltaTime, 8000, 50)
	doSnow(deltaTime)
	doSammy()
	moveNotes()
	showScore()
	moveNexus()
	doMerryGoRound(deltaTime)
	doBumperCars()
	doSantiPowerups()
	doBeaters()
	adjustClockZone()
end

  -----------------------------------------------------------//Main
function main()
	--local game = GameInfo()
	--local players = game:getPlayers()
    subscribe(Event.ShipEnteredZone)
	subscribe(Event.ShipLeftZone)
	subscribe(Event.ShipKilled)
	subscribe(Event.MsgReceived)
	subscribe(Event.ShipSpawned)
	subscribe(Event.PlayerLeft)
	subscribe(Event.Tick)
	Timer:scheduleRepeating(addGravity, 1)
	Timer:scheduleRepeating(changeElevator, 1900)
	Timer:scheduleRepeating(moveElevator, 1)
	Timer:scheduleRepeating(doGravitySink, 30)
	Timer:scheduleRepeating(doPetResourceItem, 30)
	Timer:scheduleOnce(dance, difficulty)
	fireSeeker()
	for i = 1, 50 do
		snowRes[i] = ResourceItem.new()
		snowRes[i]:setPos(point.new(-510 + math.cos(i * 3) * (220 + i),2295 + math.sin(i * 3) * (220 + i)))
		levelgen:addItem(snowRes[i])
		i=i+1
	end
	for index, value in ipairs(beaterArray) --Make the items
	do
		for i = 1, value["length"]
		do
			item = {}
			item["loc"] = value["center"]
			item["item"] = value["type"].new()
			item["item"]:setPos(value["center"])
			levelgen:addItem(item["item"])
			table.insert(value["objects"], item)
			value["center"] = point.new(value["center"].x + value["x"], value["center"].y + value["y"])
		end
	end

	
	clockZone = GoalZone.new()
	numPoints = 50
	radius = 300
	pointArray = generateClockPoints(point.new(0,0), numPoints, radius)
	cachedPointArray = copyToArray(pointArray)
	clockZone:setGeom(copyToArray(pointArray))
	bf:addItem(clockZone)
	ringCounter = 1
	decrease = true
	
end