SCORELIMIT = 7

function gamerulesThink()
	if _CurTime() > NEXTMAP then
		_ServerCommand("changelevel "..GetNextMap().."\n")
	end
	if fCTF_time <= _CurTime() and not FightMode then
		messageInfo(0, 67, 0.5, "Capture the enemy flags!!")
		StartCTF()
	elseif fCTF_len <= _CurTime() and FightMode then
		removeAllPlayersWeapons()
		for i in teams do
			if _TeamScore(i) >= SCORELIMIT then
				messageInfo(0, 67, 0.3, "Game over.\n Score limit has been reached...")
				displayWhoWon()
				EndCTF()
				return
			end
		end
		EndCTF()
	end
	if FightMode then
		for x in teams do
			for y in teams do
				if x ~= y then
					if IsInRadius(teams[x].flag, teams[y].flagpoint, 50) then
						if IsInRadius(teams[y].flag, teams[y].flagpoint, 100) then
							if teams[x].flagCarrier > 0 then
								FlagCapture(x, y)
							end
						end
					end
				end
			end
			if teams[x].flagCarrier == 0 then
				_TraceLine(_EntGetPos(teams[x].flag), vector3(0,0,-1), 32, teams[x].flag)
				if _TraceHitWorld() then
					_PlaySound("weapons/physcannon/energy_bounce1.wav")
					local entities = _EntitiesFindInSphere(_EntGetPos(teams[x].flag), 198)
					local missed = 0
					for p,ent in entities do
						if _EntGetType(ent) == "player" then
							if _PlayerInfo(ent, "team") ~= x then
								missed = ent
							end
						end
					end
					if missed == 0 then
						PrintMessageAll( "The "..teams[x].name.." flag was dropped in the field.", teams[x].color.r, teams[x].color.g, teams[x].color.b, 255)
					else
						PrintMessageAll( _PlayerInfo(missed,"name").." couldn't catch the "..teams[x].name.." flag.\nThe flag was dropped in the field.", teams[x].color.r, teams[x].color.g, teams[x].color.b, 255)
					end
					_EntSetPos(teams[x].flag, _EntGetPos(teams[x].flagpoint))
				end
			end
		end
	end
end

function onGravGunDrop(player, entity)
	if _EntGetName(entity) == "flag" then
		for i in teams do
			if teams[i].flag == entity then
				_PlaySound("weapons/physcannon/superphys_launch"..math.random(1,4)..".wav")
				PrintMessageAll(_PlayerInfo(player, "name").." dropped the "..teams[i].name.." flag.", teams[i].color.r, teams[i].color.g, teams[i].color.b, 255)
				teams[i].flagCarrier = 0
				return true
			end
		end
	end
	return true
end

function onGravGunLaunch(player, entity)
	if _EntGetName(entity) == "flag" then
		for i in teams do
			if teams[i].flag == entity then
				_PlaySound("weapons/physcannon/energy_sing_flyby1.wav")
				PrintMessageAll(_PlayerInfo(player, "name").." throws the "..teams[i].name.." flag.", teams[i].color.r, teams[i].color.g, teams[i].color.b, 255)
				teams[i].flagCarrier = 0
				local a = _PlayerGetShootAng(player) or vector3(0,0,0)
				AddTimer(0, 1, _phys.ApplyForceCenter, entity, vecMul(a, -180000))
				return true
			end
		end
	end
	return true
end
