_OpenScript("admins.txt"); --Import admins!
--_OpenScript("vip.txt"); --Import admins!
-- PropProtector v 1.3.1e
-- 
-- When a user spawns a prop, it's protected from removing and moving from other Players, except admins. Toolgun is disabled at foreign props too (still beta, but runs very well)
-- After a user disconnects, others can make his props their possession or remove/move them if the gracetime is over.
-- If the old player reconnects, he will get back his old possessions, except the timeout finished. Even, if someone else has made this prop their new possession
-- If noone wants to own the old players props, they got removed after finishing the timeout (can be disabled, of course)
--
-- New in v1.1 is the adminpanel and an easy to join kick-ass panel for players, to start a vote, for getting in into a group
-- And of course, many bugfixes and performance optimization ;)
-- 
-- New in v1.3 is the Lock/Unlock for Cars, which you can perform with the GravGun, Performance Optimisation in the ThinkFunction, and the PropProtector AI, which makes
-- Any Car/Airboat etc. a player property (maybe, this works bad in 1% of all cases, but it works good!) and the Whell/Thruster auto-property mode (makes the thrusters/wheels the property of the Ent, they are attached too)
-- And new is the HardMode ToolGun Protection. Now, player trying to exploit the protection engine get their weapons switched to "crowbar", when the hardmode is active
-- And, you cant weld/easyweld/axis/easyballsock any MapElements like func_brushes,func_doors etc.
-- Even new is a FarNess check engine for toolgun, which disallows ANY actions of the toolgoun, out of the tracelinerange of 2000 Units
-- And some optimisation has been made to Remover Engine (effects) and AdminPannel (added some stuff)
-- And the RemoveOldProps engine has been improved!
-- Added Alpha-Mode for Old props
--
-- Cleanup engine based on Anders1 "cleanup" which has been modified by aVoN (System of a pWne!^) to add SteamID support and timeout remover
-- Propprotection, Groupmode, Toolgun disabled and Inheritance for the Propprotection scripted by aVoN (System of a pWne!^)
-- Feel free to use any part of this script, with giving credits to Anders1 and aVoN

-- And of course. Added CopyGun protection support. Simply add the following code somewhere AT THE END of the SpawnCopyItem Function (~line 250)  of the copygun: _RunString("CopyGunProtectionMode(" .. newProp .. "," .. Owner .. ",".. iBufferIndex ..",".. table.getn(copyBufferTable) ..")");
-- Then, any spawned props of the copygun are now recognized of this script too.

-- ############################### CONFIG START

protect_props = true -- If set to true, all spawned props are procted before remove,move etc. -- Dont turn off, because its a major part of the script. Just set it off to test some stuff
hard_toolgun_protection_mode = false -- if this is set to true, anyones ToolGun gets switched to Crowbar, immediately, after he shot prop, which he isnt owning. Prevents the "looking at my prop, but shooting on another with easy weld" exploit, where there ISNT any available workaround!
autoremove_props = true -- This is one of the mainfunctions of this script. This automaticly removes props from people, who habve left the server, after a certain timeout
grace_period = 120 -- Time in seconds, entitys arent free for all. After this period, the timout begins!
timeout = 200.0 -- Time in Seconds, entities get removed, after a player disconnected
spawn_prop_timeout = 2 -- Time, a player can't spawn/duplicate any props after he spawned one
joinvote_timeout = 90 -- Time in seconds, a player has to wait until he can start a new vote
vote_timeout = 15 -- Time in seconds, a vote for joining a group is displayed on a players screen
vote_ratio = 0.4 -- Ammount of players needed to accept a player for joining into a group ( 1 = 100%, 0.3 = 30% and so on)
allow_toolgun_on_all_props = false -- Allows Toolgun on every prop. If set to FALSE, the toolgun is just usable at own props or props in a group - Very usefull, but still beta - But works very stable
color_props = true -- If set to true, props of disconnecting players get automaticly colored, so anyone can see, that its free for all
use_alpha_indication_instead_of_color = true -- Toggles the new alpha-mode for props. If yes, all old props get indicated with a lower alpha instead of beeing colored orange
indicate_prop = true -- Sets an indicator on the prop (a man, running away), which indicates, that this prop is free for all - set to false, to deactivate it
indicate_prop_symbol = true -- Set to true, when you need to disable the "man whos running away" symbol
indicate_prop_text = true -- Sets additionally to the indicator a text onto the prop, which says "Old owener disconnected, Own this prop by physgunning it!" - Just wokrs with indicate_props = true
show_chat_commands = true -- Toggle, if any commands done with the PropProtector (like player left etc) is announced in the chat for everyone
show_console_commands = true -- Toggle, if any commands done with the PropProtector (like player spawned an entity) is announced in the console for everyone
compatibility_mode = false -- If set to true, every prop is now protected by playernames, and not by steamid. This is needed on listenservers with the listenserverfix or lanservers - Normaly, the compatibility mode gets automaticly activated, if a lan or listenserver is detected. But if you want, you can activate it by default
prop_protector_builder_group_panel_name = "[PropProtector] Buildergroups" -- The name of the Buildergroup panel.
prop_protector_prop_manager_panel_name = "[PropProtector] Prop Manager" -- Same as above, but for the propmanager
prop_protector_admin_panel_name = "[PropProtector] AdminPanel" -- Same as above, but for the adminpanel

--ToolGun Allowed Modes - Change Modes to "false", to disallow them. Can be changed during gameplay with "toolgundisable" and "toolgunlist" (will not be safed after mapchange)
toolgun_allowed = {} -- Don't edit this!

--Rope
toolgun_allowed[0] = true
--Elastic
toolgun_allowed[1] = true
--Weld
toolgun_allowed[2] = true
--Ballsocket
toolgun_allowed[3] = true
--Pulley
toolgun_allowed[4] = true
--Easy Weld
toolgun_allowed[5] = true
--Easy Ball Socket
toolgun_allowed[6] = true
--Axis
toolgun_allowed[7] = true
--Slider
toolgun_allowed[8] = true
--Nailgun
toolgun_allowed[9] = true


--Facepuser
toolgun_allowed[10] = true
--Eyeposer
toolgun_allowed[11] = true
--Remover
toolgun_allowed[12] = true
--Ignite
toolgun_allowed[13] = false
--Paint
toolgun_allowed[14] = true
--Duplicate
toolgun_allowed[15] = false
--Color
toolgun_allowed[16] = true
--Magnetise
toolgun_allowed[17] = true
--No Collide
toolgun_allowed[18] = false
--Dynamite
toolgun_allowed[19] = false


--Material
toolgun_allowed[20] = true
--Render Target Camera
toolgun_allowed[21] = true


--This isn't a used mode, but DON'T remove this entry. Otherwise the script may create errors
toolgun_allowed[22] = true 


--Thrusters
toolgun_allowed[23] = true
--Physprops
toolgun_allowed[24] = true
--Statue
toolgun_allowed[25] = true
--Balloons
toolgun_allowed[26] = true
--Emitters
toolgun_allowed[27] = false
--Sprites
toolgun_allowed[28] = false
--Wheels
toolgun_allowed[29] = true

-- Recommended for this part to configurate is a basic knowledge in LUA - You have to know about comments,tables, and an IQ > 20 (bread) to be able to add banned Props here
--Add any Prop here, which should be banned from beeing spawnable - For example, the huge chimney. Go to the path, the model is in, and add it with whole path. Rootdirectory is gmod9!.
--To find the corret Modelnames, go to steam/your@email/sourcemods/gmod9/settings/menu_props/ to find a model in the textfiles there. Look at your mod/-modcache/ folder too, if you added custom mods
-- You can ban props by adding either the path or just the model to the list below. Using \ or / as path delemiter doesn't matter. Case sensitivity doesn't matter too.

banned_props = {
	"models/props_animated_breakable/Smokestack.mdl",
	"models/props_phx/huge/Evildisc_corp.mdl"
}

-- Add any entity class in here, which shouldn't be usable with the toolgun or physicsgun. You can also add wildcards by just using a part of the entity class. e.g "func_" will block all "func_"* related entitys
disable_complete_usage = false -- Set this to true to even disallow the usage of the physgun on these props in the list below.
disable_usage_on_following_entities = {
"func_door", -- Dont break doors
"func_door_rotating",  -- Dont break doors
"func_breakable_surf" -- Glass on e.g rp_hometown1999
}

-- ############################### CONFIG END

function isAdmin(userid)
	return userid == 1 and not _IsDedicatedServer()
end

-- Don't edit anything below, except you know, what you are doing
propprotector_version = 1.31 -- Don't change this. This indicates the Version of the proprotector for any other scripts, based on it.
if not tables_set then
	tables_set = true -- Don't change this - this is just a dummy, to prevent overwriting the entity and playertables on a scriptresatrt. Otherwise, people can't spawn and old props aren't protected anymore
	cleanupTableEntitys = {} -- Saves the entities persessions of a player
	newOwnerTableEntitys = {} -- Saves the entities for the new owner of an old prop
	playerTimeoutTable = {} -- If not 0 (0 = connected) the timeout starts, and his old pros get removed after the timeout
	playerGracetimeTable = {}
	playerTimeoutSpawnPropTable = {} -- Saves the timeout for someone, after he can spawn a new prop again
	groupCount = 1 -- Sets the first group. Gets counted up higher and higher, when a player joins
	playerGroups = {} -- Is set, so player can get into a certain group
	entityGroup = {} -- The group, an entity is in it, so other groupmembers can use them
	playerGroupsVoteTimeout = {} -- Sets the timeout for voting
	playerGroupsVotes = {} -- Counts the votes for a group
	playerGroupsVotePlayer = {} -- Saves the player, who called the vote
	playerCanShoot = {} -- Saves the information, if a player can shoot or not, to not run _PlayerDisableAttack onThink (maybe more performance)
	playerLastVote = {} -- Saves the last votetime of a player
	refresh_group_panel = {} -- Saves the information, if a panel shall be resend onKeyPressed, or not, if something in the group constallation changed. Edits here won't have any effect
	player_has_shot = {} -- Chekcks, if player has shot
	userGotThisInfo = {} -- Checks, if the player has got the message "toolgun not allowed, becausei tsn or your prop" or not
	ban_next_prop = 0 -- Saves the userid of the admin, who startet the "ban next prop" mode
	playerShootTimeoutCounter = {} -- Saves the time, a player isn't allowed to shoot with toolgun in his hand (Just needed to check the toolgun disallower - dont edit anything!)
	freeNextProp = {} -- Saves the boolean, if the next prop the player uses physgun on it will be free for all, or not
	propUnLocked = {}
	ai_check_duplicated = {}
	-- Saves the information about spawned CopyGun stuff in PropProtector
	player_remove_stuff_mode = {} -- Saves, what a layer wanna remove - Thrusters/props etc
	cgSpawnedStuff = {}
	-- Needed for the "fade in/out of text in a players sphere
	ent_having_text_on_it = {}
	for i=1,_MaxPlayers() do
		ent_having_text_on_it[i] = {}
	end
end
toolgun_player_protection = {10,13,17,18,14,16,20,24,25} -- Disabled moded on TraceHitWorld
-- Names for the Toolgunmodes - Needed for the Toolgunmode disabler menu and concommand
toolgunmode_names = {}
toolgunmode_names[0] = "Rope"
toolgunmode_names[1] = "Elastic"
toolgunmode_names[2] = "Weld"
toolgunmode_names[3] = "Ballsocket"
toolgunmode_names[4] = "Pulley"
toolgunmode_names[5] = "Easy Weld"
toolgunmode_names[6] = "Easy Ball Socket"
toolgunmode_names[7] = "Axis"
toolgunmode_names[8] = "Slider"
toolgunmode_names[9] = "Nailgun"
toolgunmode_names[10] = "Faceposer"
toolgunmode_names[11] = "Eyeposer"
toolgunmode_names[12] = "Remover"
toolgunmode_names[13] = "Ignite"
toolgunmode_names[14] = "Paint"
toolgunmode_names[15] = "Duplicate"
toolgunmode_names[16] = "Color"
toolgunmode_names[17] = "Magnetise"
toolgunmode_names[18] = "No Collide"
toolgunmode_names[19] = "Dynamite"
toolgunmode_names[20] = "Materials"
toolgunmode_names[21] = "RT Camera"
toolgunmode_names[22] = ""
toolgunmode_names[23] = "Thrusters"
toolgunmode_names[24] = "Physprops"
toolgunmode_names[25] = "Statue"
toolgunmode_names[26] = "Balloons"
toolgunmode_names[27] = "Emitters"
toolgunmode_names[28] = "Sprites"
toolgunmode_names[29] = "Wheels"


function check_for_disabled_entities(entity)
	local blocked_ents = disable_usage_on_following_entities;
	local entity_type = string.lower(_EntGetType(entity));
	for k,v in blocked_ents do
		if(string.find(entity_type,v) ~= nil) then
			return true;
		end
	end
	return false;
end

-- This function makes the script Nickname based instead of Steamid based. Needed on lanservers and listenservers with ListenServer fix installed on it, because every SteamID is STEAM_ID_LAN or UNKNOWN

function _PlayerInfoCompatibility(userid,mode)
	if(mode ~= "networkid") then
		return _PlayerInfo(userid,mode)
	else
		if(compatibility_mode == true and _IsDedicatedServer() == false) then
			return _PlayerInfo(userid,"name") -- Returns now the name instead of the nickname to the script, so listen and lanservers will work with this script too
		else
			-- First off all, check, if the script needs the compatibility mode
			network_id = _PlayerInfo(userid,"networkid")
			if(string.lower(network_id) == "unknown" or string.lower(network_id) == "steam_id_lan" or string.lower(network_id) == "steam_id_pending") then
				compatibility_mode = true -- Switch to compatibility mode now
				_Msg("[PROP] Lan/Listenserver copatibilitymode activated\n")
				return _PlayerInfo(userid,"name")
			else
				return network_id -- Otherwise return the SteamID
			end
		end
	end
end

function update_tables_on_compatibility_mode(userid,newname,oldname)
	if(compatibility_mode == true) then
		-- Check every entity for his old name, and change the old name to the new one
		for cleanupTableEntitys_key,cleanupTableEntitys_value in cleanupTableEntitys do
			if(cleanupTableEntitys_value == oldname) then
				cleanupTableEntitys[cleanupTableEntitys_key] = newname
			end
		end
		-- New owner table as well as cleanupTableEntitys
		for newOwnerTableEntitys_key,newOwnerTableEntitys_value in newOwnerTableEntitys do
			if(newOwnerTableEntitys_value == oldname) then
				newOwnerTableEntitys[newOwnerTableEntitys_key] = newname
			end
		end
		if(playerTimeoutTable[oldname] ~= nil) then
			--Timout table
			playerTimeoutTable[newname] =  playerTimeoutTable[oldname]
			playerTimeoutTable[oldname] = nil
		end
		if(playerGracetimeTable[oldname] ~= nil) then
			--Gracetime table
			playerGracetimeTable[newname] =  playerGracetimeTable[oldname]
			playerGracetimeTable[oldname] = nil
		end
		if(playerTimeoutSpawnPropTable[oldname] ~= nil) then
			--Spawntimeout table
			playerTimeoutSpawnPropTable[newname] =  playerTimeoutSpawnPropTable[oldname]
			playerTimeoutSpawnPropTable[oldname] = nil
		end
		if(playerGroups[oldname] ~= nil) then
			--Playergroup table
			playerGroups[newname] =  playerGroups[oldname]
			playerGroups[oldname] = nil
		end
		if(playerGroupsVoteTimeout[oldname] ~= nil) then
			--Votetimeout table
			playerGroupsVoteTimeout[newname] = playerGroupsVoteTimeout[oldname]
			playerGroupsVoteTimeout[oldname] = nil
		end
		if(playerGroupsVotePlayer[oldname] ~= nil) then
			--Player, who voted, to get into a group
			playerGroupsVotePlayer[newname] = playerGroupsVotePlayer[oldname]
			playerGroupsVotePlayer[oldname] = nil
		end
		if(playerCanShoot[oldname] ~= nil) then
			--Toolgun shootallow table
			playerCanShoot[newname] = playerCanShoot[oldname]
			playerCanShoot[oldname] = nil
		end
		if(playerLastVote[oldname] ~= nil) then
			--Last time, a player voted
			playerLastVote[newname] = playerLastVote[oldname]
			playerLastVote[oldname] = nil
		end
		if(player_has_shot[oldname] ~= nil) then
			--Player has shot?
			player_has_shot[newname] = player_has_shot[oldname]
			player_has_shot[oldname] = nil
		end
		if(userGotThisInfo[oldname] ~= nil) then
			--User got info on toolgunuse of one prop, he doesn't owns
			userGotThisInfo[newname] = userGotThisInfo[oldname]
			userGotThisInfo[oldname] = nil
		end
		if(freeNextProp[oldname] ~= nil) then
			--Saves, if next physgunned prop is free for all
			freeNextProp[newname] = freeNextProp[oldname]
			freeNextProp[oldname] = nil
		end
		if(playerShootTimeoutCounter[oldname] ~= nil) then
			--Toolgun shoottimeout counter
			playerShootTimeoutCounter[newname] = playerShootTimeoutCounter[oldname]
			playerShootTimeoutCounter[oldname] = nil
		end
	end
end
HookEvent("eventPlayerNameChange",update_tables_on_compatibility_mode) -- Updates the entity tables etc in compatibility mode (usernames in table instead of steamid based player recognization)

-- To Autoprotect CopyGun created props, simply add somewhere in the SpawnCopyItem Function (~line 250)  of the copygun following line: _RunString("CopyGunProtectionMode(" .. newProp .. "," .. Owner .. ",".. iBufferIndex ..",".. table.getn(copyBufferTable) ..")");
function CopyGunProtectionMode(ent,userid,curTableKey,maxTableKey)
	if(curTableKey == nil or maxTableKey == nil) then
		curTableKey = 2;
		maxTableKey = "unknown";
	else
		local cg_table_num = table.getn(cgSpawnedStuff[_PlayerInfoCompatibility(userid, "networkid")]);
		-- Generate new CopyGun Entry
		if(curTableKey == 1) then
			cgSpawnedStuff[_PlayerInfoCompatibility(userid, "networkid")][cg_table_num+1] = {}
			cg_table_num = cg_table_num + 1;
			_spawnmenu.AddItem( userid, prop_protector_prop_manager_panel_name, "+Pattern "..cg_table_num, "ppcgremovepattern "..cg_table_num )
		end
		-- Add entity to this new entry
		cgSpawnedStuff[_PlayerInfoCompatibility(userid, "networkid")][cg_table_num][table.getn(cgSpawnedStuff[_PlayerInfoCompatibility(userid, "networkid")][cg_table_num])+1] = ent;
	end
	cleanupTableEntitys[ent] = _PlayerInfoCompatibility(userid,"networkid")
	entityGroup[ent] = playerGroups[_PlayerInfoCompatibility(userid,"networkid")]
	-- Just show, that someone has copied so and so much props wqith CG => no console spam anymore!
	if(curTableKey == 1) then
		if(show_console_commands == true) then
			_PrintMessageAll( HUD_PRINTCONSOLE, "      [PROP] [CopyGun] " .. _PlayerInfoCompatibility(userid, "name") .. " (" .. _PlayerInfoCompatibility(userid, "networkid") .. ") copied "..maxTableKey.." entitys" )
		end
	end
end

-- Protection for VMFLoader stuff
function VMFProtectionMode(ent,userid)
	cleanupTableEntitys[ent] = _PlayerInfoCompatibility(userid,"networkid")
	entityGroup[ent] = playerGroups[_PlayerInfoCompatibility(userid,"networkid")]
	if(show_console_commands == true) then
		_PrintMessageAll( HUD_PRINTCONSOLE, "      [PROP] [VMFLoader] " .. _PlayerInfoCompatibility(userid, "name") .. " (" .. _PlayerInfoCompatibility(userid, "networkid") .. ") spawned " .. ent )
	end
end

--Protection for EntityCommandSuite
function ECSProtectionMode(ent,userid)
	cleanupTableEntitys[ent] = _PlayerInfoCompatibility(userid,"networkid")
	entityGroup[ent] = playerGroups[_PlayerInfoCompatibility(userid,"networkid")]
	if(show_console_commands == true) then
		_PrintMessageAll( HUD_PRINTCONSOLE, "      [PROP] [ECS] " .. _PlayerInfoCompatibility(userid, "name") .. " (" .. _PlayerInfoCompatibility(userid, "networkid") .. ") spawned " .. ent )
	end
end

function unColorEnt(ent)
	if(color_props == true) then
		if(_EntExists(ent) == true) then
			if(use_alpha_indication_instead_of_color == true) then
				_EntFire(ent,"alpha","255",0)
			else
				_EntFire(ent, "color", "255+255+255", 0)
			end
		end
	end
end
	
function colorEnt(ent)
	if(color_props == true) then
		if(_EntExists(ent) == true) then
			if(use_alpha_indication_instead_of_color == true) then
				_EntSetKeyValue(ent,"rendermode","1") -- Make it available for alpha
				_EntFire(ent,"alpha","150",0) -- Make it semitransparent now!
			else
				_EntFire(ent, "color", "255+147+0", 0)
			end
		end
	end
end

function remove_indicator_from_prop(ent)
	if(_EntGetType(ent) ~= "prop_timedexplosion") then
		unColorEnt(ent)
	end
	_GModText_Hide(0,1111 + ent)
	_GModText_Hide(0,2222 + ent)
	_GModText_Hide(0,3333 + ent)
	_GModText_Hide(0,4444 + ent)
	_GModText_Hide(0,5555 + ent)
end


function set_indicator_to_prop(to_player,entity,duration)
	if(indicate_prop == true) then
		if(_EntGetType(entity) ~= "prop_timedexplosion") then
			colorEnt(entity)
		end
		if(indicate_prop_symbol == true) then
			-- Logo above Prop- low alpha
			_GModText_Start("creditsOutroLogos")
			_GModText_SetEntity(entity)
			_GModText_SetColor(0, 255, 0, 50)
			_GModText_SetTime(0.7*duration, 2, 0.3*duration)
			_GModText_SetEntityOffset(vector3(0, 0, 70))
			_GModText_SetText("D")
			_GModText_Send(to_player, 1111 + entity)
			
			-- Logo above Prop- low alpha - getting red (for "will be removed soon")
			_GModText_Start("creditsOutroLogos")
			_GModText_SetEntity(entity)
			_GModText_SetColor(255, 0, 0, 30)
			_GModText_SetTime(duration, duration, 2)
			_GModText_SetEntityOffset(vector3(0, 0, 70))
			_GModText_SetText("D")
			_GModText_Send(to_player, 2222 + entity)
			
			-- Logo above Prop - Full alpha for first seconds
			_GModText_Start("creditsOutroLogos")
			_GModText_SetEntity(entity)
			_GModText_SetColor(0, 255, 0, 255)
			_GModText_SetTime(13, 2, 5)
			_GModText_SetEntityOffset(vector3(0, 0, 70))
			_GModText_SetText("D")
			_GModText_Send(to_player, 3333 + entity)
		end
		-- This was the old indication. Don't use it anymore!
		--[[
		if(indicate_prop_text == true) then
			-- Text on prop
			_GModText_Start( "Branding" )
			_GModText_SetEntity(entity)
			_GModText_SetColor(255, 255, 255, 170)
			_GModText_SetTime(10, 2, 2)
			_GModText_SetEntityOffset(vector3(0, 0, 0))
			_GModText_SetText("Old owner disconnected\nOwn this prop by physgunning it!")
			_GModText_Send(to_player, 4444 + entity)
		end
		--]]
	end
end

function set_indicator_to_prop_freeprop(to_player,entity,duration)
	colorEnt(entity)
	_GModText_Start("creditsOutroLogos")
	_GModText_SetEntity(entity)
	_GModText_SetColor(255, 128, 0, 100)
	_GModText_SetTime(0.7*duration, 2, 0.3*duration)
	_GModText_SetEntityOffset(vector3(0, 0, 70))
	_GModText_SetText("z")
	_GModText_Send(to_player, 1111 + entity)
	
	-- Logo above Prop - Full alpha for first seconds
	_GModText_Start("creditsOutroLogos")
	_GModText_SetEntity(entity)
	_GModText_SetColor(255, 128, 0, 255)
	_GModText_SetTime(13, 2, 5)
	_GModText_SetEntityOffset(vector3(0, 0, 70))
	_GModText_SetText("z")
	_GModText_Send(to_player, 3333 + entity)
end
-- Generates a menu, to easy start a votejoin for players

function setSpawnmenu_propmanager(userid)
	_spawnmenu.RemoveCategory( userid, prop_protector_prop_manager_panel_name ) -- Remove at first, to reset on changes (like player groups changed)
	_spawnmenu.AddItem( userid, prop_protector_prop_manager_panel_name, "@Free physgunned props", "" )
	_spawnmenu.AddItem( userid, prop_protector_prop_manager_panel_name, "+Just next prop", "freeprop" )
	_spawnmenu.AddItem( userid, prop_protector_prop_manager_panel_name, "+All next props", "freeproptoggle" )
	_spawnmenu.AddItem( userid, prop_protector_prop_manager_panel_name, "@Free all my props", "" )
	_spawnmenu.AddItem( userid, prop_protector_prop_manager_panel_name, "+Free now", "freeallmyprops" )
	_spawnmenu.AddItem( userid, prop_protector_prop_manager_panel_name, "@ ", "" )
	_spawnmenu.AddItem( userid, prop_protector_prop_manager_panel_name, "@ ", "" )
	_spawnmenu.AddItem( userid, prop_protector_prop_manager_panel_name, "@Remove my...", "" )
	_spawnmenu.AddItem( userid, prop_protector_prop_manager_panel_name, "+Everything", "removemyprops all" )
	_spawnmenu.AddItem( userid, prop_protector_prop_manager_panel_name, "+Props", "removemyprops 1" )
	_spawnmenu.AddItem( userid, prop_protector_prop_manager_panel_name, "+Vehicles", "removemyprops 2" )
	_spawnmenu.AddItem( userid, prop_protector_prop_manager_panel_name, "+Thrusters", "removemyprops 3" )
	_spawnmenu.AddItem( userid, prop_protector_prop_manager_panel_name, "+Wheels", "removemyprops 4" )
	_spawnmenu.AddItem( userid, prop_protector_prop_manager_panel_name, "+Balloons", "removemyprops 6" )
	_spawnmenu.AddItem( userid, prop_protector_prop_manager_panel_name, "+Dynamites", "removemyprops 5" )
	_spawnmenu.AddItem( userid, prop_protector_prop_manager_panel_name, "@ ", "" )
	_spawnmenu.AddItem( userid, prop_protector_prop_manager_panel_name, "@Remove CopyGun Patterns", "" )
	for k,v in cgSpawnedStuff[_PlayerInfoCompatibility(userid, "networkid")] do
		_spawnmenu.AddItem( userid, prop_protector_prop_manager_panel_name, "+Pattern "..k, "ppcgremovepattern "..k )
	end
end

function setSpawnmenu_joingroup(userid)
	_spawnmenu.RemoveCategory( userid, prop_protector_builder_group_panel_name ) -- Remove at first, to reset on changes (like player groups changed)
	_spawnmenu.AddItem( userid, prop_protector_builder_group_panel_name, "@Join a group by pressing", "" ) -- Sets the topic, to join a specific group
	_spawnmenu.AddItem( userid, prop_protector_builder_group_panel_name, "@on a players nickname", "" )
	_spawnmenu.AddItem( userid, prop_protector_builder_group_panel_name, "+Leave group", "leavegroup") -- Adds a Button to leave a group to the menu
	_spawnmenu.AddItem( userid, prop_protector_builder_group_panel_name, "@ ", "" )
	
	local group_counter = 1 -- Needed for the grouptopics (Group 1, 2, 3 etc)
	local player_groups_count = {}
	
	-- Get all users
	local player_ids = {}
	for id=1, _MaxPlayers() do
		if(_PlayerInfoCompatibility(id,"connected")) then
			-- Get connected players
			if(_PlayerInfoCompatibility(id,"networkid") ~= nil and _PlayerInfoCompatibility(id,"name") ~= nil) then
				player_ids[_PlayerInfoCompatibility(id,"networkid")] = _PlayerInfoCompatibility(id,"name")
			end
		end
	end
	
	for playerGroups_key,playerGroups_value in playerGroups do
		-- Just count active (connected) players for addingd to the grouplist later
		if(player_ids[playerGroups_key] ~= nil) then
			if(player_groups_count[playerGroups_value] == nil) then
				player_groups_count[playerGroups_value] = 1
			else
				player_groups_count[playerGroups_value] = player_groups_count[playerGroups_value] + 1
			end
		end
	end
	
	-- Set the buttons now
	for player_groups_count_key,player_groups_count_value in player_groups_count do
		if(player_groups_count[player_groups_count_key] > 1) then
			_spawnmenu.AddItem( userid, prop_protector_builder_group_panel_name, "@Group " .. group_counter, "" )
			group_counter = group_counter + 1
			for playerGroups_key,playerGroups_value in playerGroups do
				if(playerGroups_value == player_groups_count_key) then
					if(playerGroups_key ~= nil and player_ids[playerGroups_key] ~= nil) then
						_spawnmenu.AddItem( userid, prop_protector_builder_group_panel_name, "+" .. player_ids[playerGroups_key], "joingroup " .. player_ids[playerGroups_key] )
					end
				end
			end
			player_groups_count[player_groups_count_key] = nil -- Now unset the old - All groups, who have just one player in it,  will be put to unassigned
		end
	end
	
	local show_unassigned = true
	for player_groups_count_key,player_groups_count_value in player_groups_count do
		-- Just show the Unassigned, if no assigned people exists
		if(show_unassigned == true) then
			_spawnmenu.AddItem( userid, prop_protector_builder_group_panel_name, "@Unassigned", "" )
			show_unassigned = false
		end
		for playerGroups_key,playerGroups_value in playerGroups do
			if(playerGroups_value == player_groups_count_key) then
				if(playerGroups_key ~= nil and player_ids[playerGroups_key] ~= nil) then
					_spawnmenu.AddItem( userid, prop_protector_builder_group_panel_name, "+" .. player_ids[playerGroups_key], "joingroup " .. player_ids[playerGroups_key] )
				end
			end
		end
	end
end

function setSpawnmenu_adminpanel(userid)
	_spawnmenu.RemoveCategory( userid, prop_protector_admin_panel_name ) -- Remove at first, to reset on changes (like player groups changed) - Now, the old is removed, and paler gets redirected to temp panel, created before
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "@Admin Panel", "" )
	-- Cleanup section
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "@Banning", "" )
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+(Un)Ban next spawned", "bannextspawnedprop" )
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "@Cleanup map", "" )
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+Remove old props", "cleanupold" )
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+Remove ALL PROPS", "cleanupall" )
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "@Specific Cleanup", "" )
	
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+Props ", "cleanupmode 0" )
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+Ragdolls ", "cleanupmode 4" )
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+Player Corpses", "cleanupmode 21" )
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+Vehicles ", "cleanupmode 15" )
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+NPCs and Spawners", "cleanupmode 14" )
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+Dynamites ", "cleanupmode 13" )
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+Balloons ", "cleanupmode 1" )
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+Welds ", "cleanupmode 20" )
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+Thrusters ", "cleanupmode 2" )
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+Sprites and Effects ", "cleanupmode 3" )
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+Ropes and Pulley ", "cleanupmode 6" )
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+Emitters ", "cleanupmode 7" )
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+Ammo ", "cleanupmode 16" )
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+Weapons ", "cleanupmode 17" )
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+Combine Balls ", "cleanupmode 18" )
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+Fires ", "cleanupmode 11" )
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+Physboxes ", "cleanupmode 5" )
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+Smoketrails ", "cleanupmode 8" )
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+Firetrails ", "cleanupmode 9" )
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+Flares ", "cleanupmode 10" )
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+Sparklers ", "cleanupmode 12" )
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+Beams ", "cleanupmode 19" )
	
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "@Script Config", "" )
	if(autoremove_props == true) then
		autoremove_props_topic = "ON"
	else
		autoremove_props_topic = "OFF"
	end
	if(protect_props == true) then
		protect_props_topic = "ON"
	else
		protect_props_topic = "OFF"
	end
	
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+Propprotection " .. protect_props_topic, "propprotectortoggle" )
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+Autoremover " .. autoremove_props_topic, "autoremovetoggle" )
	
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "@Prop indication", "" )
	if(indicate_prop == true) then
		indicate_prop_activated = "ON"
	else
		indicate_prop_activated = "OFF"
	end
	if(indicate_prop_text == true) then
		indicate_prop_text_activated = "ON"
	else
		indicate_prop_text_activated = "OFF"
	end
	if(color_props == true) then
		color_props_activated = "ON"
	else
		color_props_activated = "OFF"
	end
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+Indicate props " .. indicate_prop_activated, "indicatepropstoggle" )
	-- Just show this Options, when the Indicate Props var is set to true
	if(indicate_prop == true) then
		_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+Text on props " .. indicate_prop_text_activated, "proptexttoggle" )
		_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+Color on props " .. color_props_activated, "colorpropstoggle" )
	end
	
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "@ ", "" )
	
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "@Toolgun (not remover) allowed...", "" )
	if(allow_toolgun_on_all_props == true) then
		tool_gun_allowed = "On all props"
	else
		tool_gun_allowed = "Just on own props"
	end
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+" .. tool_gun_allowed, "toolguntoggle" )
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "@Toolgunmodes", "" )
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+Disable all modes", "toolgundisable off" )
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+Allow all modes", "toolgundisable on" )
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "@   Activated modes", "" )
	for i=0,29 do
		if(toolgun_allowed[i] == true) then
			if(toolgunmode_names[i] ~= "") then -- Exclude the no 22 (unused mode)
				_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+" .. toolgunmode_names[i], "toolgundisable " .. i )
			end
		end
	end
	_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "@   Deactivated modes", "" )
	for i=0,29 do
		if(toolgun_allowed[i] == false) then
			if(toolgunmode_names[i] ~= "") then -- Exclude the no 22 (unused mode)
				_spawnmenu.AddItem( userid, prop_protector_admin_panel_name, "+" .. toolgunmode_names[i], "toolgundisable " .. i )
			end
		end
	end
end

-- Initialiate players

function player_created (userid)
	-- Set the vars, which are needed for the script to work with the player
	playerTimeoutTable[_PlayerInfoCompatibility(userid,"networkid")] = nil
	playerGracetimeTable[_PlayerInfoCompatibility(userid,"networkid")] = nil
	playerTimeoutSpawnPropTable[_PlayerInfoCompatibility(userid,"networkid")] = _CurTime() -- Set the next timestamp, the player can spawn a prop
	playerCanShoot[_PlayerInfoCompatibility(userid,"networkid")] = true -- Set player enabled too shoot - Setting this to false hasn't any effect. Just needed, to just don call the _PlayerDisableAttack function onThink
	playerLastVote[_PlayerInfoCompatibility(userid,"networkid")] = 0 -- Start the votetimout
	refresh_group_panel[_PlayerInfoCompatibility(userid,"networkid")] = false -- sets to false, so the panel wont refresh on next keypress
	player_has_shot[_PlayerInfoCompatibility(userid,"networkid")] = false -- Needed for the toolgun checker.
	userGotThisInfo[_PlayerInfoCompatibility(userid,"networkid")] = false -- toggles, whenever a player tried to use the toolgun on a pro, he doesn't owns
	playerShootTimeoutCounter[_PlayerInfoCompatibility(userid,"networkid")] = 0
	freeNextProp[_PlayerInfoCompatibility(userid,"networkid")] = false
	cgSpawnedStuff[_PlayerInfoCompatibility(userid,"networkid")] = {}
	
	-- Put player in a group
	if(playerGroups[_PlayerInfoCompatibility(userid,"networkid")] == nil) then
		playerGroups[_PlayerInfoCompatibility(userid,"networkid")] = groupCount -- Put someoe into a group
		groupCount = groupCount +1 -- Increase group counter index
	end
	
	-- Remove indicators from his old props -- Done too with the function at the bottom but its safier to run this function too
	for player_spawnreset_key,player_spawnreset_value in cleanupTableEntitys do
		if(player_spawnreset_value == _PlayerInfoCompatibility(userid,"networkid")) then
			newOwnerTableEntitys[player_spawnreset_key] = nil -- Reset new owner
			remove_indicator_from_prop(player_spawnreset_key) -- Remove indicators on respawn
		end
	end
	-- Remove indicators from groupprops
	-- Remove indicators from his old props -- Done too with the function at the bottom
	for player_spawnreset_key,player_spawnreset_value in entityGroup do
		if(player_spawnreset_value == playerGroups[_PlayerInfoCompatibility(userid,"networkid")]) then
			remove_indicator_from_prop(player_spawnreset_key) -- Remove indicators on respawn
		end
	end
	-- Unset timeouts for any players in group, if ONE member of the group is on the server.
	-- This is needed. because, if every member is gone from server, but one rejoins, the timeout of the others wont stop. Just his own would stop. So the groupprops will be deleted
	
	-- Get all users
	local player_ids = {}
	for i=1, _MaxPlayers() do
		if(_PlayerInfoCompatibility(i,"connected")) then
			player_ids[_PlayerInfoCompatibility(i,"networkid")] = true
			-- Get connected players
		end
	end
	
	for playerGroups_key,playerGroups_value in playerGroups do
		if(playerGroups_value == playerGroups[_PlayerInfoCompatibility(userid,"networkid")] and playerGroups_key ~= _PlayerInfoCompatibility(userid,"networkid")) then
			-- Found players in same group. Now, delete the Timeout.
			playerTimeoutTable[playerGroups_key] = nil;
			if(player_ids[playerGroups_key] ~= true) then
				playerGracetimeTable[playerGroups_key] = grace_period + _CurTime() -- Set gracetime start - Bur gracetime wont stop, when still players are in the group
			end
		end
	end
	remove_indicator_from_prop(userid) -- Don't make a player accidently a "unowned prop" :D - happend in earlier Betatimes - should be fixed at the moment, but its safier do let this do.
	if(show_console_commands == true) then
		player_name_temp = string.lower(_PlayerInfoCompatibility(userid,"name"))
		-- Don't announce this for connecting mingebags. Most server autokick Minges, so don't announce them, that they are connecting/disconnecting all the time.
		if(string.find(player_name_temp,"minge") == nil) then
			_PrintMessageAll( HUD_PRINTCONSOLE, "      [PROP] " .. _PlayerInfoCompatibility(userid, "name") .. " (" .. _PlayerInfoCompatibility(userid, "networkid") .. ") initialized" )
		end
	end
	if(isAdmin(userid) == true) then
		setSpawnmenu_adminpanel(userid) -- Send the adminpanel to the admin
	end
	setSpawnmenu_joingroup(userid) -- Send the JoinGroup menu to this players
	setSpawnmenu_propmanager(userid) -- The propmanager
	set_refresh_grouppanel() -- Refrehs all players group panels
	_Msg("[PROP] " .. _PlayerInfoCompatibility(userid, "name") .. " (" .. _PlayerInfoCompatibility(userid, "networkid") .. ") initialized\n")
end
HookEvent("eventPlayerInitialSpawn", player_created) --  Register player

function resend_grouppanel(userid,key)
	if(refresh_group_panel[_PlayerInfoCompatibility(userid,"networkid")] == true) then
		setSpawnmenu_joingroup(userid)
		refresh_group_panel[_PlayerInfoCompatibility(userid,"networkid")] = false
	end
end
HookEvent("eventKeyPressed", resend_grouppanel) -- Resend the group panel to player, if changed, only if he has released a key

function set_refresh_grouppanel()
	-- Sets the needed table for all players to true, so the joingroup panel respawns on next keypressed
	for refresh_group_panel_key,refresh_group_panel_value in refresh_group_panel do
		refresh_group_panel[refresh_group_panel_key] = true
	end
end

-- Prop Owner Checking with SWEP wrapper

-- prop_protectionSWEPwrapper(<userid> , <shot/aimed entity> , <id of the weapon => MyIndex> , <swep function to run> )

function prop_protectionSWEPWrapper(userid,entity,swep_id,swep_function)
	local runstring = swep_function.."("..tostring(prop_protection (userid,entity))..")"
	_SWEPRunString (swep_id,runstring)
end

function prop_protection (userid,entity)
	if(disable_complete_usage == true) then
		if(check_for_disabled_entities(entity) == true and isAdmin(userid) == false) then
			return false;
		end
	end
	-- Get all usernames
	player_names = {}
	for i=1, _MaxPlayers() do
		if(_PlayerInfoCompatibility(i,"connected")) then
			player_names[_PlayerInfoCompatibility(i,"networkid")] = _PlayerInfoCompatibility(i,"name")
			-- Get connected players
		end
	end
	-- Allow player to use this prop, because he is an recognized admin or the script is turned off
	if(isAdmin(userid) == true or protect_props == false) then
		-- Shows the admin the name of the Owner of a prop
		if(player_names[cleanupTableEntitys[entity]] ~= nil and cleanupTableEntitys[entity] ~= _PlayerInfoCompatibility(userid,"networkid")) then
			_GModText_Start("Default")
			_GModText_SetPos(0.02, 0.02)
			_GModText_SetColor( 255, 255, 255, 200 )
			_GModText_SetTime( 2, 0, 0.5 )
			_GModText_SetText( "Owner: " .. player_names[cleanupTableEntitys[entity]])
			_GModText_SetDelay( 0 )
			_GModText_Send( userid, 96 )
			_GModRect_Hide(userid, 404, 0 , 0)
			_GModRect_Start("gmod/white")
			_GModRect_SetPos(0.01, 0.01, 0.3, 0.04)
			_GModRect_SetColor(0, 0, 0, 150)
			_GModRect_SetTime(2, 0, 0.5)
			_GModRect_Send(userid, 402)
		end
		return true
	end
	-- Allow player to use this prop, because noone owns it (e.g. map autospawned props like cars)
	if(cleanupTableEntitys[entity] == nil) then
		return true
	end
	-- Allow player to use this prop, because the old player disconnected and timeout finished
	if(playerTimeoutTable[cleanupTableEntitys[entity]] ~= nil) then
		if(playerTimeoutTable[cleanupTableEntitys[entity]] > 0 and (newOwnerTableEntitys[entity] == _PlayerInfoCompatibility(userid,"networkid") or newOwnerTableEntitys[entity] == nil)) then
			return true
		end
	end
	-- Allow player to use this prop, because he is in the buildergroup, which owns this prop
	if(entityGroup[entity] == playerGroups[_PlayerInfoCompatibility(userid,"networkid")]) then
		return true
	end
	-- Allow the player to use this prop, because its his property
	if(cleanupTableEntitys[entity] == _PlayerInfoCompatibility(userid,"networkid")) then
		-- Prop removable if the player is an Admin, or the player who spawned this prop or if the player has disconnected
		return true
	else
		_GModText_Start("CloseCaption_Bold")
		_GModText_SetPos(0.23, 0.40)
		_GModText_SetColor( 255, 255, 255, 200 )
		_GModText_SetTime( 2, 0, 0 )
		if(player_names[cleanupTableEntitys[entity]] == nil) then
			_GModText_SetText( "Sorry ".._PlayerInfoCompatibility(userid,"name")..", but this prop isn't yours!" )
		else
			_GModText_SetText( "Sorry ".._PlayerInfoCompatibility(userid,"name")..", but this prop belongs to " .. player_names[cleanupTableEntitys[entity]] .. "!" )
		end
		_GModText_SetDelay( 0 )
		_GModText_Send( userid, 99 )
		prop_message_rect( userid ,2)
		return false
	end
end

function eventPlayerUseEntity(userid,entity)
	if(string.find(_EntGetType(entity),"vehicle") ~= nil) then
		if(physgun_action(userid,entity)) then
			local lock_status = "LOCKED";
			_GModText_Start("CloseCaption_Bold")
			_GModText_SetPos(0, 1)
			_GModText_SetColor( 255, 255, 255, 200 )
			_GModText_SetTime( 5, 0, 0.5 )
			if(VEHICLE_TABLE_ALLOW_OTHERS[entity] == true or (_EntGetType(entity) == "prop_vehicle_prisoner_pod" and VEHICLE_TABLE_ALLOW_OTHERS[entity] == nil)) then
				lock_status = "UNLOCKED";
			end
			_GModText_SetText( "You can lock/unlock this vehicle with gravity gun - Status: "..lock_status )
			_GModText_SetDelay( 0 )
			_GModText_Send( userid, 99 )
			return false;
		else
			if(VEHICLE_TABLE_ALLOW_OTHERS[entity] == true or (_EntGetType(entity) == "prop_vehicle_prisoner_pod" and VEHICLE_TABLE_ALLOW_OTHERS[entity] == nil)) then
				return false;
			else
				_GModText_Start("CloseCaption_Bold")
				_GModText_SetPos(0.23, 0.40)
				_GModText_SetColor( 255, 255, 255, 200 )
				_GModText_SetTime( 2, 0, 0 )
				_GModText_SetText( "Sorry ".._PlayerInfoCompatibility(userid,"name")..", but this vehicle is locked!" )
				_GModText_SetDelay( 0 )
				_GModText_Send( userid, 99 )
				prop_message_rect( userid ,2)
				return true; -- Thats a bit weird ^^ 
			end
		end
	else
		return false;
	end
end

function onPlayerRemove(userid,entity) -- Delete Prop protection
	if(entity ~= nil) then
		if(prop_protection (userid,entity) == true) then
			remove_entity_out_of_cgspawnlist(cleanupTableEntitys[entity],entity);
			cleanupTableEntitys[entity] = nil -- Delete the entity out of the index to prevent collusions
			newOwnerTableEntitys[entity] = nil -- unset new Owner entity because of the same reason
			entityGroup[entity] = nil
			-- If this entity got a flag, so remove the old flag
			remove_indicator_from_prop(entity)
			return true
		else
			return false
		end
	else
		--Noone owns it
		return true
	end
end

VEHICLE_TABLE_ALLOW_OTHERS = {}
function onGravGunPunt(userid,entity) --  Gravitygun puntprotection
	if(entity ~= nil) then
		if(prop_protection (userid,entity)) then
			-- Locking of vehicles for others
			if(cleanupTableEntitys[entity] ~= nil) then
				if(string.find(_EntGetType(entity),"vehicle") ~= nil) then
					_GModText_Start("CloseCaption_Bold")
					_GModText_SetTime( 3, 0, 0 )
					_GModText_SetPos(0.23, 0.40)
					if(VEHICLE_TABLE_ALLOW_OTHERS[entity] == true or (_EntGetType(entity) == "prop_vehicle_prisoner_pod" and VEHICLE_TABLE_ALLOW_OTHERS[entity] == nil)) then
						_GModText_SetColor( 255, 0, 0, 200 )
						_GModText_SetText( "Vehicle locked! Just you can use it now!" )
						VEHICLE_TABLE_ALLOW_OTHERS[entity] = false;
					else
						_GModText_SetColor( 0, 255, 0, 200 )
						_GModText_SetText( "You unlocked this vehicle! Anyone can use it now!" )
						VEHICLE_TABLE_ALLOW_OTHERS[entity] = true;
					end
					prop_message_rect( userid , 3)
					_GModText_SetDelay( 0 )
					_GModText_Send( userid, 99 )
					return false;
				end
			end
			return true;
		else
			return false;
		end
	else
		return true
	end
end

function onGravGunPickup(userid,entity) --  Gravitygun pickup protection
	if(entity ~= nil) then
		return prop_protection (userid,entity)
	else
		return true
	end
end

function onGravGunLaunch(userid,entity) --  Gravitygun launch protection
	if(entity ~= nil) then
		return prop_protection (userid,entity)
	else
		return true
	end
end

function onGravGunDrop(userid,entity) --  Gravitygun drop protection
	if(entity ~= nil) then
		return prop_protection (userid,entity)
	else
		return true
	end
end

-- New Owner Part

function make_new_owner(userid,entity,dont_allow_new_owner_ship)
	if(check_for_disabled_entities(entity) == true) then return false end;
	if(dont_allow_new_owner_ship ~= true) then -- Dont let the player, who has just "unlocked" this prop make him the new owner immediately after he has done this
		local new_owner = 0
		-- Unowned props get a new owner - just allow on props and non maps entities - There was a bug, allowing player to own other players and/or map entities like brushes
		if(cleanupTableEntitys[entity] == nil and _EntGetType(entity) ~= "player" and _EntGetType(entity) ~= "func_brush" and string.find(_EntGetModel(entity),"*") == nil) then
			cleanupTableEntitys[entity] = _PlayerInfoCompatibility(userid,"networkid")
			entityGroup[entity] = playerGroups[_PlayerInfoCompatibility(userid,"networkid")] -- Put the new entity into the group
			new_owner = 1
		else
			if(playerTimeoutTable[cleanupTableEntitys[entity]] ~= nil) then
				if(playerTimeoutTable[cleanupTableEntitys[entity]] > 0 and newOwnerTableEntitys[entity] == nil) then
					newOwnerTableEntitys[entity] = _PlayerInfoCompatibility(userid,"networkid") -- New owner set. He will be the owner of this prop, after the countdown has bee done!
					-- The entity is put into the group after the timeout has finshed. During this time, noone of the group except the new owner can handle this props
					new_owner = 2
				end
			end
		end
		if(new_owner > 0) then
			_GModText_Start("CloseCaption_Bold")
			_GModText_SetTime( 3, 0, 0 )
			if(new_owner == 1) then
				_GModText_SetPos(0.23, 0.40)
				_GModText_SetColor( 255, 255, 255, 200 )
				_GModText_SetText( "You are now the new owner of this prop! Enjoy!" )
			else
				_GModText_SetPos(0.23, 0.379)
				_GModText_SetColor( 255, 147, 0, 200 )
				_GModText_SetText( "You are now the new owner of this prop\nunless the old owner reconnects! Enjoy!" )
			end
			prop_message_rect( userid , 3)
			_GModText_SetDelay( 0 )
			_GModText_Send( userid, 99 )
			_PlaySoundPlayer(userid,"gmod/pop.wav") -- Indicates, that this player is now the new owner of this prop
			remove_indicator_from_prop(entity) -- Hide entity Texts/Flags
			return true
		else
			return false
		end
	else
		return false
	end
end

function physgun_action(userid,entity)
	if(entity ~= nil) then
		dont_allow_new_owner_ship = false
		if(propUnLocked[_PlayerInfoCompatibility(userid,"networkid") .. entity] ~= nil) then
			if(propUnLocked[_PlayerInfoCompatibility(userid,"networkid") .. entity] > _CurTime()) then
				dont_allow_new_owner_ship = true
			end
		end
		if(make_new_owner(userid,entity,dont_allow_new_owner_ship)) then
			-- Make the Player own the "free" physgunned object, but dont let the user use it immediately after overtake! (maybe freezed prop is falling down?)
			return true
		else
			if(prop_protection (userid,entity) == true) then
				if(freeNextProp[_PlayerInfoCompatibility(userid,"networkid")] ~= false) then
					-- Now check, if the prop is really one of this owner or one of the groups one
					if(newOwnerTableEntitys[entity] ~= _PlayerInfoCompatibility(userid,"networkid") and (cleanupTableEntitys[entity] == _PlayerInfoCompatibility(userid,"networkid") or entityGroup[entity] == playerGroups[_PlayerInfoCompatibility(userid,"networkid")])) then
						-- Make the physgunned prop free for all now
						entityGroup[entity] = nil
						newOwnerTableEntitys[entity] = nil
						cleanupTableEntitys[entity] = nil
						_GModText_Hide(userid, 99)
						_GModRect_Hide(userid, 406, 0.5, 0)
						_GModText_Start("CloseCaption_Bold")
						_GModText_SetPos(0.23, 0.40)
						_GModText_SetTime( 3, 0, 0 )
						_GModText_SetColor( 0, 255, 0, 200 )
						_GModText_SetText( "The prop you physgunned is now free for all!" )
						_GModText_SetDelay( 0 )
						_GModText_Send( userid, 99 )
						prop_message_rect( userid , 3)
						set_indicator_to_prop_freeprop(0,entity,60)
						propUnLocked[_PlayerInfoCompatibility(userid,"networkid") .. entity] = 5 + _CurTime() -- Player can't get this prop back to 5 seconds.
						_PlaySoundPlayer(userid,"gmod/pop.wav") -- Indicates, that this player is now the new owner of this prop
					end
					if(freeNextProp[_PlayerInfoCompatibility(userid,"networkid")] ~= 2) then
						-- Dont turn of this mode, because we are in togglemode now
						freeNextProp[_PlayerInfoCompatibility(userid,"networkid")] = false
					end
					return false
				else
					return true
				end
			else
				return false
			end
		end
	else
		return true
	end
end

function onPhysPickup(userid,entity) --  Physgun Pickup protection
	return physgun_action(userid,entity)
end

function onPhysFreeze(userid,entity) --  Physgun Freeze protection
	return physgun_action(userid,entity)
end

--Anti Spam Protector and Bannedprop checkup

function add_prop_to_ban_list(userid,prop) -- Adds props to the banlist
	_GModRect_Hide(userid, 407, 0, 0)
	_GModText_Start("CloseCaption_Bold")
	_GModText_SetPos(0.23, 0.40)
	_GModText_SetTime( 5, 0, 0 )
	_GModText_SetDelay( 0 )
	prop_old = prop
	prop = string.gsub(string.gsub(string.lower(prop),"\\",""),"/","") -- Remove all \ and / out of the name
	for banned_props_key,banned_props_value in banned_props do
		-- Find banned props in the currently spawned prop
		banned_props_value = string.gsub(string.gsub(string.lower(banned_props_value),"\\",""),"/","")
		if(string.find(prop,banned_props_value)) then
			-- We found it still in list: It's currently banned - So remove it now
			banned_props[banned_props_key] = nil
			_GModText_SetColor( 0, 255, 0, 200 )
			_GModText_SetText( "The prop you spawned is now unbanned and available for spawning again" )
			_GModText_Send( userid, 99 )
			prop_message_rect(userid,5,404)
			if(show_console_commands == true) then
				_PrintMessageAll( HUD_PRINTCONSOLE, "      [PROP] ".. _PlayerInfoCompatibility(userid,"name") .." unbanned prop " .. prop_old )
			end
			if(show_chat_commands == true) then
				_PrintMessageAll( HUD_PRINTTALK, "[PROP] ".. _PlayerInfoCompatibility(userid,"name") .." unbanned prop " .. prop_old )
			end
			return true
		end
	end
	-- Add this banned prop now, if it wasn't found in the search above
	table.insert(banned_props,table.getn(banned_props),prop_old)
	_GModText_SetColor( 255, 0, 0, 200 )
	_GModText_SetText( "The prop you spawned is now banned from spawning" )
	_GModText_Send( userid, 99 )
	prop_message_rect(userid,5,404)
	if(show_console_commands == true) then
		_PrintMessageAll( HUD_PRINTCONSOLE, "      [PROP] ".. _PlayerInfoCompatibility(userid,"name") .." banned prop " .. prop_old )
	end
	if(show_chat_commands == true) then
		_PrintMessageAll( HUD_PRINTTALK, "[PROP] ".. _PlayerInfoCompatibility(userid,"name") .." banned prop " .. prop_old )
	end
end

function prop_is_banned(prop) -- Checks for a banned prop
	-- Check for a banned prop now
	prop = string.gsub(string.gsub(string.lower(prop),"\\",""),"/","") -- Remove all \ and / out of the name
	for banned_props_key,banned_props_value in banned_props do
		-- Find banned props in the currently spawned prop
		banned_props_value = string.gsub(string.gsub(string.lower(banned_props_value),"\\",""),"/","")
		if(string.find(prop,banned_props_value)) then
			return true
		end
	end
	return false
end

function ban_next_spawned_prop(userid,arg)
	if(isAdmin(userid) == true) then
		if(ban_next_prop ~= userid) then
			ban_next_prop = userid
			_GModText_Start("CloseCaption_Bold")
			_GModText_SetPos(0.23, 0.40)
			_GModText_SetColor( 255, 128, 0, 200 )
			_GModText_SetTime( 9999, 0, 0 )
			_GModText_SetText( "The next prop you spawn will be (un)banned" )
			_GModText_SetDelay( 0 )
			_GModText_Send( userid, 99 )
			prop_message_rect(userid,9999,407)
		else
			_GModRect_Hide(userid, 407, 0, 0)
			_GModText_Hide(userid, 99)
			ban_next_prop = 0
		end
	end
end

CONCOMMAND("bannextspawnedprop",ban_next_spawned_prop)

function prop_spawn_antispam (userid, entity)
	if(tonumber(entity) ~= nil) then
		entity = _EntGetModel(entity);
	end
	if(ban_next_prop == userid and entity ~= nil) then
		add_prop_to_ban_list(userid,entity)
		ban_next_prop = 0
		return false
	end
	if(prop_is_banned(entity) and isAdmin(userid) == false) then
		_GModText_Start("CloseCaption_Bold")
		_GModText_SetPos(0.23, 0.40)
		_GModText_SetColor( 255, 255, 255, 200 )
		_GModText_SetTime( 2, 0, 0 )
		_GModText_SetText( "This prop is banned. You can't spawn it!" )
		_GModText_SetDelay( 0 )
		_GModText_Send( userid, 99 )
		prop_message_rect( userid , 2)
		return false
	end
	-- Inform the admin about the current prop, that it's banned
	if(prop_is_banned(entity) and isAdmin(userid) == true) then
		_GModText_Start("CloseCaption_Bold")
		_GModText_SetPos(0.23, 0.40)
		_GModText_SetColor( 255, 0, 0, 200 )
		_GModText_SetTime( 2, 0, 0 )
		_GModText_SetText( "This prop is banned except for admins" )
		_GModText_SetDelay( 0 )
		_GModText_Send( userid, 99 )
		prop_message_rect( userid , 2)
	end
	-- Prevents a possible bug (i actually don't know why it happens), which makes spawning unable
	if(playerTimeoutSpawnPropTable[_PlayerInfoCompatibility(userid,"networkid")] == nil) then
		playerTimeoutSpawnPropTable[_PlayerInfoCompatibility(userid,"networkid")] = _CurTime() -- Set new timestamp
	end
	if(playerTimeoutSpawnPropTable[_PlayerInfoCompatibility(userid,"networkid")] < _CurTime()  or isAdmin(userid) == true) then
		playerTimeoutSpawnPropTable[_PlayerInfoCompatibility(userid,"networkid")] = _CurTime() + spawn_prop_timeout -- Set new timestamp
		if(show_console_commands == true) then
			_PrintMessageAll( HUD_PRINTCONSOLE, "      [PROP] " .. _PlayerInfoCompatibility(userid, "name") .. " (" .. _PlayerInfoCompatibility(userid, "networkid") .. ") spawned entity ".. entity ) -- Prints Info into the console so the admin can look for the one,  who is doing shit
		end
		return true
	else
		_GModText_Start("CloseCaption_Bold")
		_GModText_SetPos(0.23, 0.40)
		_GModText_SetColor( 255, 255, 255, 200 )
		_GModText_SetTime( 2, 0, 0 )
		_GModText_SetText( "You just can spawn props every " .. spawn_prop_timeout .. " seconds!" )
		_GModText_SetDelay( 0 )
		_GModText_Send( userid, 99 )
		prop_message_rect( userid , 2)
		return false
	end
end

function eventPlayerSpawnProp(userid,entity) -- Spawning Props
	return prop_spawn_antispam (userid, entity)
end
function eventPlayerDuplicateProp(userid,entity) -- Dublicating Props
	if(prop_spawn_antispam (userid, entity)) then
		ai_check_duplicated[userid] = entity;
		return true;
	end
	return false;
end
function eventPlayerSpawnRagdoll(userid,entity) -- Spawning Ragdolls
	--return ragdoll_allowed(userid,entity)
	return prop_spawn_antispam (userid, entity);
end
function eventPlayerDuplicateRagdoll(userid,entity) -- Dublicating Ragdoll
	if(prop_spawn_antispam (userid, entity)) then
		ai_check_duplicated[userid] = entity;
		return true;
	end
	return false;
end
-- I'm using this on my own server - ignore it
--[[
function ragdoll_allowed(userid,entity)
	local is_admin_on_server = false;
	for pl=1,_MaxPlayers() do
		if(_PlayerInfoCompatibility(pl,"connected")) then
			if(isAdmin(pl) == true) then
				is_admin_on_server = true;
				break;
			end
		end
	end
	if(isAdmin(userid) == true or isVip(userid) == true or is_admin_on_server == true) then
		return prop_spawn_antispam (userid, entity)
	else
		_GModText_Start("CloseCaption_Bold")
		_GModText_SetPos(0.23, 0.40)
		_GModText_SetTime( 5, 0, 0 )
		_GModText_SetColor( 255, 255, 255, 200 )
		_GModText_SetText( "Due to performance issues, ragdolls are allowed for VIPs only or when an admin is online" )
		_GModText_SetDelay( 0 )
		_GModText_Send( userid, 99 )
		prop_message_rect( userid , 5)
		return false
	end
end
-- Spawnprop/ragdoll Autoprotection
--]]
function prop_spawned(userid, entity)
	cleanupTableEntitys[entity] = _PlayerInfoCompatibility(userid,"networkid") -- Add new entity to players index
	entityGroup[entity] = playerGroups[_PlayerInfoCompatibility(userid,"networkid")] -- Put the new entity into the group of the users
	-- If there is still, for what reasen ever, a text registered to this entity id - remove it!
	remove_indicator_from_prop(entity)
end

HookEvent("eventPlayerPropSpawned", prop_spawned) -- Spawning Props
HookEvent("eventPlayerRagdollSpawned",prop_spawned) -- Spawning Ragdolls

-- Delete props - section

function player_disconnects (name, userid, address, steamid, reason)
	set_refresh_grouppanel() -- Send the JoinGroup menu to all players and update it onKeyPressed
	if(compatibility_mode == true) then
		use_id = name
	else
		use_id = steamid
	end
	playerGracetimeTable[use_id] = grace_period + _CurTime()
	-- If he is in a group with active players in it, don't send this message to all.
	all_players = {}
	for i=1,_MaxPlayers() do
		if(_PlayerInfoCompatibility(i,"connected")) then
			all_players[_PlayerInfoCompatibility(i,"networkid")] = true
			-- Get connected players
		end
	end
	send_gracetime_message = true
	for playerGroups_key,playerGroups_value in playerGroups do
		if(playerGroups_key ~= use_id and playerGroups[use_id] == playerGroups_value) then
			if(all_players[playerGroups_key] ~= nil) then
				-- We found a player in the group, the disconnected player was - Dont send the GraceTime message to all players!
				send_gracetime_message = false
				break
			end
		end
	end
	-- Don't send the gracetime message, if the player hasn't had any props.
	owns_props = false
	for cleanupTableEntitys_key,cleanupTableEntitys_value in cleanupTableEntitys do
		if(cleanupTableEntitys_value == use_id) then
			owns_props = true
			break
		end
	end
	if(send_gracetime_message == true and owns_props == true) then
		--stop blocked mingefags ermm, MingeBags from spamming the chat ;D - good for Servers with ULX protected MingeAntiConnect.
		player_name_temp = string.lower(name)
		if(string.find(player_name_temp,"minge") == nil) then
			if(show_console_commands == true) then
				_PrintMessageAll( HUD_PRINTCONSOLE, "      [PROP] "..name.." left - starting gracetime of "..grace_period.." seconds for his props" )
			end
			if(show_chat_commands == true) then
				_PrintMessageAll( HUD_PRINTTALK, "[PROP] "..name.." left - starting gracetime of "..grace_period.." seconds for his props" )
			end
		end
		_Msg("[PROP] "..name.." left - starting gracetime of "..grace_period.." seconds for his props\n")
	end
end
HookEvent("eventPlayerDisconnect",player_disconnects) -- player disconnectes - now the Timeout will start


function remove_unused_props()
	-- delete all non existent props from the entityList to prevent following problem: Someone owns a prop - he magnetises it (now its getting a new ent ID)
	-- Now someone else spawns a prop with the ID of the old non magnetised entity ID - he wont be able to use it... So, all nonexitent Ents have to be erased out of the index
	for delete_nonexistent_key,delete_nonexistent_value in cleanupTableEntitys do
		if(_EntExists(delete_nonexistent_key) == false or _EntGetType(delete_nonexistent_key) == "player") then
			--_PrintMessageAll( HUD_PRINTCONSOLE, "[PROP] Non existant propID got removed")
			-- Delete regular non existent props
			remove_entity_out_of_cgspawnlist(cleanupTableEntitys[delete_nonexistent_key],delete_nonexistent_key)
			cleanupTableEntitys[delete_nonexistent_key] = nil
			VEHICLE_TABLE_ALLOW_OTHERS[delete_nonexistent_key] = nil;
			-- and if inherit, delete this prop enty too
			newOwnerTableEntitys[delete_nonexistent_key] = nil
			-- delete entity out of group
			entityGroup[delete_nonexistent_key] = nil -- Put the new entity into the group
			remove_indicator_from_prop(delete_nonexistent_key) -- remove availbale flag ids
		end
	end
	
	-- Get all users
	local player_ids = {}
	for id=1, _MaxPlayers() do
		if(_PlayerInfoCompatibility(id,"connected")) then
			player_ids[_PlayerInfoCompatibility(id,"networkid")] = true
			-- Get connected players
		end
	end
	
	current_time_temp = _CurTime() -- Save this for not running _CurTime() all the time (performance plus, maybe)
	
	-- Setting gracetime and starting timeout after gracetime
	for playerGracetimeTable_key,playerGracetimeTable_value in playerGracetimeTable do
		if(playerGracetimeTable_value < current_time_temp) then
			-- First, check, if he is the only one in a group. So dont start the countdown
			local dont_start_timeout = false
			for group_key,group_value in playerGroups do
				if(group_value == playerGroups[playerGracetimeTable_key] and group_key ~= playerGracetimeTable_key and player_ids[group_key] == true) then
					dont_start_timeout = true -- Dont start the timeout, because somone other is in the players group
					playerGracetimeTable[playerGracetimeTable_key] = grace_period + current_time_temp -- Reset the Gracetime, so, if a group now leaves, they have gracetime too.
					break
				end
			end
			if(dont_start_timeout == false) then
				-- Start the Timeout
				playerTimeoutTable[playerGracetimeTable_key] = timeout + current_time_temp
				playerGracetimeTable[playerGracetimeTable_key] = nil -- Unset this now
				--Set the props of this owner as "free for all" now
				for player_starttimeout_key,player_starttimeout_value in cleanupTableEntitys do
					if(player_starttimeout_value == playerGracetimeTable_key) then
						if(_EntExists(player_starttimeout_key) and _EntGetType(player_starttimeout_key) ~= "player") then
							set_indicator_to_prop(0,player_starttimeout_key,timeout)
						end
					end
				end
				-- Set "newowner" props as "ownable" for all again
				for newowner_timeout_key,newowner_timeout_value in newOwnerTableEntitys do
					if(newowner_timeout_value == playerGracetimeTable_key) then
						newOwnerTableEntitys[newowner_timeout_key] = nil -- Reome new ownership of a prop - its free for all now again
						if(_EntExists(newowner_timeout_key) and _EntGetType(newowner_timeout_key) ~= "player") then
							-- Shows the indicator to the prop, someone was the newowner just for the time, the old owner countdown actually is at
							set_indicator_to_prop(0,newowner_timeout_key,playerTimeoutTable[cleanupTableEntitys[newowner_timeout_key]] - current_time_temp)
						end
					end
				end
			end
		end
	end
	
	-- Remove unlock timers
	for propUnLocked_key,propUnLocked_value in propUnLocked do
		if(propUnLocked_value <= current_time_temp) then
			propUnLocked[propUnLocked_key] = nil
		end
	end
	
	-- delete props from old owners after a countdown
	for timeout_finished_key,timeout_finished_value in playerTimeoutTable do
		if(timeout_finished_value > 0 and timeout_finished_value < current_time_temp) then
			-- Remove the entities of this playerTimeoutTable
			remove_prop_now(timeout_finished_key)
			playerTimeoutTable[timeout_finished_key] = nil
		end
	end
end

function remove_prop_now(steamid)
	for timeout_remove_key,timeout_remove_value in cleanupTableEntitys do
		if(timeout_remove_value == steamid) then
			if(_EntExists(timeout_remove_key)) then
				if(newOwnerTableEntitys[timeout_remove_key] == nil) then
					--Old Objects get removed
					if(autoremove_props == true) then
						_EffectInit();
							_EffectSetOrigin( _EntGetPos( timeout_remove_key ) );
							_EffectSetScale( 0.5 );
							_EffectSetMagnitude( 2 );
							_EffectSetRadius( 1 );
						_EffectDispatch( "cball_explode" );
						_EntRemove(timeout_remove_key)
					end
					cleanupTableEntitys[timeout_remove_key] = nil
					entityGroup[timeout_remove_key] = nil
				else
					-- Set New Owner
					cleanupTableEntitys[timeout_remove_key] = newOwnerTableEntitys[timeout_remove_key] -- Register Prop to the new steamid
					newOwnerTableEntitys[timeout_remove_key] = nil
					entityGroup[timeout_remove_key] = playerGroups[newOwnerTableEntitys[timeout_remove_key]] -- Set the group of the entity to the new users one
				end
			end
			remove_indicator_from_prop(timeout_remove_key) -- Unset flags for old props
		end
	end
end

-- Checks every player, if he is actually wearing a toolgun, and if the traced entity is his own
last_shot_ent = {}
function check_toolgun_allowed()
	for iv=1, _MaxPlayers() do
		if(_PlayerInfoCompatibility(iv,"connected") and _PlayerInfoCompatibility(iv,"alive")) then
			local user_active_weapon = string.lower(_EntGetType(_PlayerGetActiveWeapon(iv)))
			--User has toolgun in his hand
			local active_toolgun_mode = tonumber(_GetClientConVar_String(iv,"gm_toolmode"))
			local toolgun_user_id = _PlayerInfoCompatibility(iv,"networkid")
			if(last_shot_ent[toolgun_user_id] == nil) then
				last_shot_ent[toolgun_user_id] = 0;
			end
			if(user_active_weapon == "weapon_tool") then
				_TraceLine(_PlayerGetShootPos(iv),_PlayerGetShootAng(iv), 2048, iv) -- Starting the traceline
				if(_TraceHitNonWorld()) then -- We hit an entity!
					local entity = _TraceGetEnt()
					-- Map Entity check!
					if(check_for_disabled_entities(entity) == true and isAdmin(iv) == false) then
						if(playerCanShoot[toolgun_user_id] == true) then -- The player was able to shoot the entity before - Disable shooting for him now!
							playerCanShoot[toolgun_user_id] = false
							_PlayerDisableAttack(iv,true) -- Enable the toolgun for this prop
							_PlayerSelectWeapon(iv,"weapon_crowbar") -- Change the players active weapon to crowbar, to protect the other player
							if(hard_toolgun_protection_mode ~= true) then -- Hardmode activated - Dont switch back!
								_PlayerSelectWeapon(iv,"weapon_tool") -- Now, switchback to the toolgun.
							end
						end
					end
					if(active_toolgun_mode == 2) then
						if(_EntGetType(entity) == "func_door") then -- Dont allow Welding of doors, so they are unable to open
							if(playerCanShoot[toolgun_user_id] == true) then -- The player was able to shoot the entity before - Disable shooting for him now!
								playerCanShoot[toolgun_user_id] = false
								_PlayerDisableAttack(iv,true) -- Enable the toolgun for this prop
								_PlayerSelectWeapon(iv,"weapon_crowbar") -- Change the players active weapon to crowbar, to protect the other player
								if(hard_toolgun_protection_mode ~= true) then -- Hardmode activated - Dont switch back!
									_PlayerSelectWeapon(iv,"weapon_tool") -- Now, switchback to the toolgun.
								end
							end
						end
					end
					if(active_toolgun_mode == 5 or active_toolgun_mode == 6 or active_toolgun_mode == 7) then -- Player is holding Easy Weld,Easy Ballsocket or Axis on his hand, which can destroy map entitys!
						if(string.find(_EntGetType(entity),"func") ~= nil) then
							-- Its a mapentity - disable toolgun on it!
							if(playerCanShoot[toolgun_user_id] == true) then -- The player was able to shoot the entity before - Disable shooting for him now!
								playerCanShoot[toolgun_user_id] = false
								_PlayerDisableAttack(iv,true) -- Enable the toolgun for this prop
								_PlayerSelectWeapon(iv,"weapon_crowbar") -- Change the players active weapon to crowbar, to protect the other player
								if(hard_toolgun_protection_mode ~= true) then -- Hardmode activated - Dont switch back!
									_PlayerSelectWeapon(iv,"weapon_tool") -- Now, switchback to the toolgun.
								end
							end
						end
					end
					if(last_shot_ent[toolgun_user_id] ~= entity) then -- The new entity isnt the same as the one before!
						if(playerCanShoot[toolgun_user_id] == true) then -- The player was able to shoot the entity before - Disable shooting for him now!
							playerCanShoot[toolgun_user_id] = false
							_PlayerDisableAttack(iv,true) -- Enable the toolgun for this prop
							-- And switch his weapon to Crowbar, and then toolgun again - shout disable exploiting as well!
							if(not ((isAdmin(iv) or cleanupTableEntitys[entity] == toolgun_user_id or newOwnerTableEntitys[entity] == toolgun_user_id or cleanupTableEntitys[entity] == nil or entityGroup[entity] == playerGroups[toolgun_user_id] or protect_props == false or allow_toolgun_on_all_props == true) and _EntGetType(entity) ~= "player")) then
								_PlayerSelectWeapon(iv,"weapon_crowbar") -- Change the players active weapon to crowbar, to protect the other player
								if(hard_toolgun_protection_mode ~= true) then -- Hardmode activated - Dont switch back!
									_PlayerSelectWeapon(iv,"weapon_tool") -- Now, switchback to the toolgun.
								end
							else
								playerCanShoot[toolgun_user_id] = true
								_PlayerDisableAttack(iv,false) -- Enable the toolgun for this prop
							end
						end
					end
					last_shot_ent[toolgun_user_id] = entity;
					-- Now an extra check. If player is in use with the "shootkey" (pressed it) and the entity infront of him is a player, his weaopon will switch to crowbar, to protect the player before accidently being colored, materialized or whatever (just some certain modes)
					if(_PlayerIsKeyDown (iv, IN_ATTACK) == true) then
						if(_EntGetType(entity) == "player") then
						--if(string.find(_EntGetType(entity),"npc_") ~= nil) then -- This line is just for me, to test the script on NPCs
							for toolgun_player_protection_key,toolgun_player_protection_value in toolgun_player_protection do
								if(active_toolgun_mode == toolgun_player_protection_value) then
									playerCanShoot[toolgun_user_id] = false
									_PlayerDisableAttack(iv,true) -- Enable the toolgun for this prop
									_PlayerSelectWeapon(iv,"weapon_crowbar") -- Change the players active weapon to crowbar, to protect the other player
									if(hard_toolgun_protection_mode ~= true) then -- Hardmode activated - Dont switch back!
										_PlayerSelectWeapon(iv,"weapon_tool") -- Now, switchback to the toolgun.
									end
									break
								end
							end
						end
						player_has_shot[toolgun_user_id] = true
					else
						player_has_shot[toolgun_user_id] = false
					end
					-- Checks, if old player disconnected, and timeout has started
					if(cleanupTableEntitys[entity] ~= nil) then
						if(playerTimeoutTable[cleanupTableEntitys[entity]] ~= nil) then
							player_disconnected = true
						else
							player_disconnected = false
						end
					end
					-- And of course - Disallow toolgun on players (e.g. material on players!) and other props, the player don't owns :D
					if((isAdmin(iv) or cleanupTableEntitys[entity] == toolgun_user_id or newOwnerTableEntitys[entity] == toolgun_user_id or cleanupTableEntitys[entity] == nil or entityGroup[entity] == playerGroups[toolgun_user_id] or protect_props == false or player_disconnected == true or allow_toolgun_on_all_props == true) and _EntGetType(entity) ~= "player") then
					--if((isAdmin(iv) or cleanupTableEntitys[entity] == _PlayerInfoCompatibility(iv,"networkid") or newOwnerTableEntitys[entity] == _PlayerInfoCompatibility(iv,"networkid") or cleanupTableEntitys[entity] == nil or entityGroup[entity] == playerGroups[_PlayerInfoCompatibility(iv,"networkid")] or protect_props == false or player_disconnected == true or allow_toolgun_on_all_props == true) and string.find(_EntGetType(entity),"npc_") == nil) then -- This line is just for me, to test the script on NPCs
						if(playerCanShoot[toolgun_user_id] == false) then
							if(player_has_shot[toolgun_user_id] == false) then
								playerCanShoot[toolgun_user_id] = true
								_PlayerDisableAttack(iv,false) -- Enable the toolgun for this prop
							end
						end
						if(userGotThisInfo[toolgun_user_id] == true) then
							userGotThisInfo[toolgun_user_id] = false
						end
					else
						if(playerCanShoot[toolgun_user_id] == true) then
							if(_PlayerIsKeyDown (iv, IN_ATTACK) == true and _EntGetType(entity) ~= "player" and userGotThisInfo[toolgun_user_id] == false) then
								userGotThisInfo[toolgun_user_id] = true
								prop_protection(iv,entity) -- Shows the player, if he is allowed to shoot on this prop or not - Just show one time, while aimed and shoot at the prop, he doesn't owns
							end
							playerCanShoot[toolgun_user_id] = false
							_PlayerDisableAttack(iv,true) -- Disable it for this prop
							_PlayerSelectWeapon(iv,"weapon_crowbar") -- Change the players active weapon to crowbar, to protect the other player
							if(hard_toolgun_protection_mode ~= true) then -- Hardmode activated - Dont switch back!
								_PlayerSelectWeapon(iv,"weapon_tool") -- Now, switchback to the toolgun.
							end
						end
					end
				else
					if(vecLength(vecSub(_PlayerGetShootPos(iv),_TraceEndPos())) >= 1948 --[[and active_toolgun_mode ~= 0 and active_toolgun_mode ~= 1 --]] and active_toolgun_mode ~= 8 and active_toolgun_mode ~= 21) then -- Slider/RT Cam is the onlyone ToolMode, which is allowed over Big distances
						-- Player is out of range - Disable Toolgun at all!
						if(playerCanShoot[toolgun_user_id] == true) then -- The player was able to shoot the entity before - Disable shooting for him now!
							playerCanShoot[toolgun_user_id] = false
							-- He tries to shoot into farness - switch weapon - otherwise, just deactivate!
							if(_PlayerIsKeyDown (iv, IN_ATTACK) == true) then
								_PlayerDisableAttack(iv,true) -- Enable the toolgun for this prop
								_PlayerSelectWeapon(iv,"weapon_crowbar") -- Change the players active weapon to crowbar, to protect the other player
								_PlayerSelectWeapon(iv,"weapon_tool") -- Now, switchback to the toolgun.
							else
								_PlayerDisableAttack(iv,true) -- Enable the toolgun for this prop
							end
						end
					else
						if(userGotThisInfo[toolgun_user_id] == true) then
							userGotThisInfo[toolgun_user_id] = false
						end
						--Prevent now ppl from holding down "shoot" while not aimed at a prop.
						--if(_PlayerIsKeyDown (iv, IN_ATTACK) == true) then
							for toolgun_player_protection_key,toolgun_player_protection_value in toolgun_player_protection do
								if(active_toolgun_mode == toolgun_player_protection_value) then
									playerShootTimeoutCounter[toolgun_user_id] = 0
									playerCanShoot[toolgun_user_id] = false
									_PlayerDisableAttack(iv,true) -- Disable it for this prop (all the time) - exploit fix
									_PlayerSelectWeapon(iv,"weapon_crowbar") -- Change the players active weapon to crowbar, to protect the other player
									--if(hard_toolgun_protection_mode ~= true) then -- Hardmode activated - Dont switch back!
									_PlayerSelectWeapon(iv,"weapon_tool") -- Now, switchback to the toolgun.
									--end
								end
							end
						--end
						if(_PlayerIsKeyDown (iv, IN_ATTACK) == false and player_has_shot[toolgun_user_id] == false) then
							if(playerShootTimeoutCounter[toolgun_user_id] < 30) then
								playerShootTimeoutCounter[toolgun_user_id] = playerShootTimeoutCounter[toolgun_user_id] + 1
							end
							-- Reenable shooting now, if still disallowed, after a wait of 6 rounds
							if(playerShootTimeoutCounter[toolgun_user_id] >= 30) then
								if(playerCanShoot[toolgun_user_id] == false) then
									playerCanShoot[toolgun_user_id] = true
									_PlayerDisableAttack(iv,false) -- Enable shooting again, if maybe a player ran into an other players view. Now the other players attack is disabled and won't get reenabled until he looks at his prop again. This breaks e.g. EasyWelding actions etc
								end
							end
						end
					end
				end
			else
				if(userGotThisInfo[toolgun_user_id] == true) then
					userGotThisInfo[toolgun_user_id] = false
				end
				if(playerCanShoot[toolgun_user_id] == false) then
					playerCanShoot[toolgun_user_id] = true
					_PlayerDisableAttack(iv,false) -- Enable shooting for any other SWEP
				end
			end
			-- Now the check, if he is allowed to use a blocked ToolGun mode
			if user_active_weapon == "weapon_tool" and not isAdmin(iv) then
				-- Check for toolgun mode allowed
				if toolgun_allowed[active_toolgun_mode] ~= true then
					_PlayerSelectWeapon(iv,"weapon_crowbar") -- Change the players active weapon to crowbar, to disable the toolmode
					_GModText_Start("CloseCaption_Bold")
					_GModText_SetPos(0.23, 0.40)
					_GModText_SetColor( 255, 255, 255, 200 )
					_GModText_SetTime( 2, 0, 0 )
					_GModText_SetText( "You aren't allowed to use this toolgun mode!" )
					_GModText_SetDelay( 0 )
					_GModText_Send( iv, 99 )
					prop_message_rect( iv , 2)
				end
			end
		end
	end
end

function check_group_vote()
	for playerGroupsVotes_key, playerGroupsVotes_value in playerGroupsVoteTimeout do
		-- Vote finished - now decide to let him in or not
		if(playerGroupsVotes_value ~= nil) then
			if(playerGroupsVotes_value < _CurTime() and playerGroupsVotes_value ~= nil and playerGroupsVotes_value ~= 0) then
				local player_group_count = 0
				for ie=1, _MaxPlayers() do
					if(_PlayerInfoCompatibility(ie,"connected") and playerGroups[_PlayerInfoCompatibility(ie,"networkid")] == playerGroupsVotes_key) then
						player_group_count = player_group_count + 1
					end
				end
				if(playerGroupsVotes[playerGroupsVotes_key] >= player_group_count*vote_ratio) then
					join_group(playerGroupsVotePlayer[playerGroupsVotes_key],playerGroupsVotes_key) -- Players is allowed to join the group
					_GModText_Start("CloseCaption_Bold")
					_GModText_SetPos(0.23, 0.40)
					_GModText_SetTime(5, 1, 0.5)
					_GModText_SetText("The vote was positive. You joined the group")
					_GModText_SetColor(0, 255, 0, 200)
					_GModText_Send(playerGroupsVotePlayer[playerGroupsVotes_key], 405)
					prop_message_rect( playerGroupsVotePlayer[playerGroupsVotes_key] , 5)
				else
					_GModText_Start("CloseCaption_Bold")
					_GModText_SetPos(0.23, 0.40)
					_GModText_SetTime(5, 1, 0.5)
					_GModText_SetText("The vote failed. You haven't joined the group")
					_GModText_SetColor(255, 200, 50, 200)
					_GModText_Send(playerGroupsVotePlayer[playerGroupsVotes_key], 405)
					prop_message_rect( playerGroupsVotePlayer[playerGroupsVotes_key] , 5)
				end
				playerGroupsVotes[playerGroupsVotes_key] = 0
				playerGroupsVotePlayer[playerGroupsVotes_key] = nil
				playerGroupsVoteTimeout[playerGroupsVotes_key] = nil
			end
		end
	end
end

-- Fades in/out the indication of the props
function set_text_on_old_near_ents()
	--if(indicate_prop == true) then
		for i=1,_MaxPlayers() do
			if(_PlayerInfoCompatibility(i,"connected") and _PlayerInfoCompatibility(i,"alive")) then
			local current_found_ents = {}
			local props = _EntitiesFindInSphere(_PlayerGetShootPos(i),300);
				for prop_k,prop_v in props do
					-- Entity is owned by someone
					if(cleanupTableEntitys[prop_v] ~= nil and newOwnerTableEntitys[prop_v] == nil) then
						-- Check, if player has left the building
						if(playerTimeoutTable[cleanupTableEntitys[prop_v]] ~= nil) then
							-- Text on prop
							current_found_ents[prop_v] = true
							-- check, if the user still sees the text (dont reset it!)
							if(ent_having_text_on_it[i][prop_v] == nil) then
								if(indicate_prop_text == true) then
									_GModText_Start( "Branding" )
									_GModText_SetEntity(prop_v)
									_GModText_SetColor(255, 255, 255, 170)
									_GModText_SetTime(99999,1, 0)
									_GModText_SetEntityOffset(vector3(0, 0, 0))
									_GModText_SetText("Old owner disconnected\nOwn this prop by physgunning it!")
									_GModText_Send(i, 4444 + prop_v)
									ent_having_text_on_it[i][prop_v] = true
								end
								-- Logo above Prop- low alpha
								_GModText_Start("creditsOutroLogos")
								_GModText_SetEntity(prop_v)
								_GModText_SetColor(0, 255, 0, 255)
								_GModText_SetTime(99999, 1, 0)
								_GModText_SetEntityOffset(vector3(0, 0, 70))
								_GModText_SetText("D")
								_GModText_Send(i, 5555 + prop_v)
							end
						end
					end
				end
					-- Remove old texts from the ents now
				for et_k,et_v in ent_having_text_on_it[i] do
					if(current_found_ents[et_k] == nil) then
						ent_having_text_on_it[i][et_k] = nil
						if(indicate_prop_text == true) then
							_GModText_Hide(i,4444 + et_k,1)
						end
						_GModText_Hide(i,5555 + et_k,1)
					end
				end
			end
		end
	--end
end

--AI Function, which checks for thrusters/wheels on props, to set them to a player and make them protected. For cars too!
function prop_protector_ai()
	--Car AutoProtection
	vehicle_ai();
	-- That was only the car AI ^^
	-- Now the Thruster/Wheel AI, which is much easier to write ;)
	thruster_ai();
	-- Duplicated PropAI
	duplicate_ai();
end

function vehicle_ai()
	local car_table = {"prop_vehicle_prisoner_pod","prop_vehicle_airboat","prop_vehicle_jeep","prop_timedexplosion","physics_thruster","prop_wheel","physics_balloon"} -- Do not only cars - Same for Dynamite,thrusters,wheels - Additionally to the thrusterAI
	for ek,ev in car_table do
		for k,v in _EntitiesFindByClass(ev) do
			local found_players = {};
			if(cleanupTableEntitys[v] == nil) then -- This vehicle isnt owned by anyone!
				-- Frist stage, which checks with a Traceline/FindInSphere combination for ONE owner!
				for pk=1,_MaxPlayers() do
					if(_PlayerInfo(pk,"connected") == true and _PlayerInfo(pk,"alive") == true) then
						_TraceLine(_PlayerGetShootPos(pk),_PlayerGetShootAng(pk), 900, pk) -- Starting the traceline
						for sphk,sphv in _EntitiesFindInSphere(_TraceEndPos(),80) do
							if(sphv == v) then -- The players traceline hit the Car, so, he is mostly the owner of it!
								found_players[(table.getn(found_players)+1)] = pk;
								break;
							end
						end
					end
				end
				-- Its just one player, who hit it, so, he is mostly the owner!
				if(table.getn(found_players) == 1) then
					-- Exactly one player found! Make him the owner now!
					cleanupTableEntitys[v] = _PlayerInfoCompatibility(found_players[1],"networkid");
					entityGroup[v] = playerGroups[_PlayerInfoCompatibility(found_players[1],"networkid")];
				else -- STAGE two - we havent found (for what fucking reason ever!) one or more VALID players! - Make the player, who is the nearest to the VEHICLE the owner of it!
					local found_near_players = {}
					-- Otherwise check for near players!
					---Max farness
					local max_farness = 400;
					for pk=1,_MaxPlayers() do
						if(_PlayerInfo(pk,"connected") == true and _PlayerInfo(pk,"alive") == true) then
							local farness = vecLength(vecSub(_EntGetPos(v),_EntGetPos(pk)));
							if(farness <= max_farness) then -- Just recognize players, which are nearer then 400 units
								max_farness = farness; -- Set new MaxFarness
								found_near_players[(table.getn(found_near_players)+1)] = pk;
							end
						end
					end
					if(table.getn(found_near_players) == 1) then -- We exactly found just ONE owner! Make him the owner now
						cleanupTableEntitys[v] = _PlayerInfoCompatibility(found_near_players[1],"networkid");
						entityGroup[v] = playerGroups[_PlayerInfoCompatibility(found_near_players[1],"networkid")];
					end -- Ok, at this point, we havent found ONE player aiming at the vewhicle, and we havent found ONE player, who is the nearest to it. - So, wait for another round, or until the real owner uses PhysGun on it to make it his property - AI can't be perfect, but it nearly works perfectly
				end
			end
		end
	end
end

function thruster_ai()
	local check_table = {"physics_thruster","prop_wheel"}
	local entity_type = ""
	for ck,cv in check_table do
		for k,v in _EntitiesFindByClass(cv) do
			if(cleanupTableEntitys[v] == nil) then -- This thursterwheel isnt owned by anyone!
				local found_near_ents = {}
				for fk,fv in _EntitiesFindInSphere(_EntGetPos(v),20) do
					entity_type = _EntGetType(fv);
					if(entity_type == "prop_physics" or entity_type == "phys_magnet" or entity_type == "prop_vehicle_prisoner_pod" or entity_type == "prop_vehicle_airboat" or entity_type == "prop_vehicle_jeep") then -- I cant think, why a thruster/wheel is attached to a "NON" prop_physics! - Ahh nevermind: phys_magnet and the vehicles :D
						if(cleanupTableEntitys[fv] ~= nil) then
							found_near_ents[(table.getn(found_near_ents) +1)] = fv;
						end
					end
				end
				for ffk,ffv in found_near_ents do
					cleanupTableEntitys[v] = cleanupTableEntitys[ffv]; -- May work sometimes a bit fucked up - but should mostly work corretly!
				end
			end
		end
	end
end

checks_for_user = {}
function duplicate_ai()
	for userid,entity in ai_check_duplicated do
		local ent_type = _EntGetModel(entity);
		--_Msg(ent_type.."\n");
		for k,v in _EntitiesFindInSphere(_EntGetPos(userid),1000) do
			if(cleanupTableEntitys[v] == nil) then
				if(_EntGetModel(v) == ent_type) then
					--_Msg(v.."\n");
					cleanupTableEntitys[v] = _PlayerInfoCompatibility(userid,"networkid");
					entityGroup[v] = playerGroups[_PlayerInfoCompatibility(userid,"networkid")];
					ai_check_duplicated[userid] = nil;
				end
			end
		end
		if(checks_for_user[userid] == nil) then
			checks_for_user[userid] = 20;
		else
			checks_for_user[userid] = checks_for_user[userid] - 1;
		end
		if(checks_for_user[userid] <= 0) then
			checks_for_user[userid] = nil;
			ai_check_duplicated[userid] = nil;
		end
	end
end

function remove_entity_out_of_cgspawnlist(steamid,entity)
	local cg_check_table = cgSpawnedStuff[steamid];
	local resend_list = false;
	if(cgSpawnedStuff[steamid] ~= nil) then
		for k,v in cg_check_table do
			for kk,vv in v do
				if(vv == entity) then
					cgSpawnedStuff[steamid][k][kk] = nil;
				end
			end
			if(table.getn(cgSpawnedStuff[steamid][k]) == 0) then
				cgSpawnedStuff[steamid][k] = nil;
				local new_cg_table = {}
				for k,v in cgSpawnedStuff[steamid] do
					new_cg_table[table.getn(new_cg_table)+1] = v;
				end
				cgSpawnedStuff[steamid] = new_cg_table;
				resend_list = true;
			end
		end
	end
	if(resend_list == true) then
		for k=1,_MaxPlayers() do
			if(_PlayerInfo(k,"connected")) then
				if(_PlayerInfoCompatibility(k,"networkid") == steamid) then
					setSpawnmenu_propmanager(k);
				end
			end
		end
	end
end

last_frame_called = 0;
ai_last_check = 0;
last_frame_called_stage_two = 0;
function PropProtectorThink()
	check_toolgun_allowed(); -- Check, if the user is allowed, to use the toolgun on the traced entity - Needs to be called EVERY frame
	if(ai_last_check >= 20) then -- To reduce lag etc, just do this every 20th frame
		prop_protector_ai();
		ai_last_check = 0;
	else
		ai_last_check = ai_last_check + 1;
	end
	if(last_frame_called >= 60) then -- Just call every 60 frames. Increaes performance!
		set_text_on_old_near_ents() -- Chekcs for old entites near a players sphere
		last_frame_called = 0;
	else
		last_frame_called = last_frame_called + 1
	end
	if(last_frame_called_stage_two >= 100) then -- Just call every 100 frames. Increaes performance!
		remove_unused_props() -- Starts the countdowntimer script
		check_group_vote() -- Checks the group votings
		last_frame_called_stage_two = 0;
	else
		last_frame_called_stage_two = last_frame_called_stage_two + 1;
	end
end
AddThinkFunction(PropProtectorThink)

-- Join/leave system

function join_group(userid,group)
	playerGroups[_PlayerInfoCompatibility(userid,"networkid")] = group -- Set him into the group
	-- Now put his props into the group
	for entity_key,entity_value in cleanupTableEntitys do
		if(entity_value == _PlayerInfoCompatibility(userid,"networkid")) then
			entityGroup[entity_key] = group -- Set the prop now into the group
		end
	end
	-- Player joined the group - Update the Groupmenu now
	set_refresh_grouppanel() -- Send the JoinGroup menu to all players and update it on keyPressed
end

function leave_group(userid)
	playerGroups[_PlayerInfoCompatibility(userid,"networkid")] = groupCount -- Put someoe into a group
	groupCount = groupCount + 1 -- Increase group counter index
	-- Now put his props into the group
	for entity_key,entity_value in cleanupTableEntitys do
		if(entity_value == _PlayerInfoCompatibility(userid,"networkid")) then
			entityGroup[entity_key] = playerGroups[_PlayerInfoCompatibility(userid,"networkid")] -- Set the prop now into the new group
		end
	end
	set_refresh_grouppanel() -- Send the JoinGroup menu to all players and update it on keyPressed
end

-- Vote System Texts
function prop_send_text(userid,text)
	_GModText_Start("CloseCaption_Bold")
	_GModText_SetPos(0.23, 0.40)
	_GModText_SetTime(5, 1, 0.5)
	_GModText_SetText(text)
	_GModText_SetColor(255, 255, 255, 200)
	_GModText_Send(userid, 405)
	prop_message_rect( userid , 6.5)
end

function prop_votejoin(userid, text)
	if(text ~= nil) then
		-- Check, if player hasn't started a vote in the last X Seconds (votespamm protection)
		if(playerLastVote[_PlayerInfoCompatibility(userid,"networkid")] < _CurTime()) then
			playerLastVote[_PlayerInfoCompatibility(userid,"networkid")] = joinvote_timeout + _CurTime()
			-- Now, start a vote, to get into the group
			-- Get the group by playername
			local found_player = false
			for ix=1, _MaxPlayers() do
				if(_PlayerInfoCompatibility(ix,"connected")) then
					if(string.find(string.lower(_PlayerInfoCompatibility(ix,"name")), string.lower(text), 1, true)) then
						found_player = true
						found_player_group = playerGroups[_PlayerInfoCompatibility(ix,"networkid")]
					end
				end
			end
			-- Don't start a vote, if the player is still in this group
			if(playerGroups[_PlayerInfoCompatibility(userid,"networkid")] ~= found_player_group) then
				if(found_player == true) then
					-- Now start the vote for all players in the group, if a group has been found
					if(playerGroupsVotePlayer[found_player_group] == nil) then
						playerGroupsVoteTimeout[found_player_group] = vote_timeout + _CurTime()
						playerGroupsVotes[found_player_group] = 0
						playerGroupsVotePlayer[found_player_group] = userid
						for ix=1, _MaxPlayers() do
							if(_PlayerInfoCompatibility(ix,"connected")) then
								if(playerGroups[_PlayerInfoCompatibility(ix,"networkid")] == found_player_group) then
									PropPlayerMenu(ix,"Allow " .. _PlayerInfoCompatibility(userid,"name") .. "\nto join your group?","PropPlayerChoose")
									_PrintMessage(ix,HUD_PRINTTALK,"[PROP] " .. _PlayerInfoCompatibility(userid,"name") .. " started a groupjoin vote")
								end
							end
						end
						_PrintMessage(userid,HUD_PRINTTALK,"[PROP] " .. _PlayerInfoCompatibility(userid,"name") .. " started a groupjoin vote")
					else
						_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] A vote is still started - Wait until it's finished")
						prop_send_text(userid,"A vote is still started - Wait until it's finished")
					end
				else
					_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] No such username for joining a group: " .. text)
					prop_send_text(userid,"No such username for joining a group: " .. text)
				end
			else
				_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] You are still in this group")
				prop_send_text(userid,"You are still in this group")
			end
		else
			wait_time = math.ceil(playerLastVote[_PlayerInfoCompatibility(userid,"networkid")] - _CurTime())
			_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] You have to wait " .. wait_time .. " seconds, until you can start a new vote")
			prop_send_text(userid,"You have to wait " .. wait_time .. " seconds, until you can start a new vote")
		end
	end
end

function prop_leavegroupe(userid,text)
	leave_group(userid)
	_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] You sucessfully left the group")
	prop_send_text(userid,"You sucessfully left the group")
end

CONCOMMAND("joingroup",prop_votejoin)
CONCOMMAND("leavegroup",prop_leavegroupe)

function show_toolgun_modes(userid,arg)
	_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] IDs for Toolgunmodes: \n")
	if(isAdmin(userid) == true) then
		_PrintMessage(userid,HUD_PRINTCONSOLE,"Use \"off\" to disable all or \"on\" to enable all")
	end
	_PrintMessage(userid,HUD_PRINTCONSOLE,"ID Name            Status")
	local activated_toolgun_mode = {}
	for toolgun_allowed_key,toolgun_allowed_value in toolgun_allowed do
		if(toolgun_allowed_value == true) then
			activated_toolgun_mode[toolgun_allowed_key] = "ACTIVATED"
		else
			activated_toolgun_mode[toolgun_allowed_key] = "deactivated"
		end
		if(toolgunmode_names[toolgun_allowed_key] ~= "") then -- Exclude the no 22 (unused mode)
			_PrintMessage(userid,HUD_PRINTCONSOLE,toolgun_allowed_key .. ": " .. toolgunmode_names[toolgun_allowed_key] .. " : " .. activated_toolgun_mode[toolgun_allowed_key])
		end
	end
end

function disable_toolgun_mode(userid,arg)
	if(isAdmin(userid) == true) then
		if(string.lower(arg) == "off" or string.lower(arg) == "on") then
			if(string.lower(arg) == "off") then
				for toolgun_allowed_key,toolgun_allowed_value in toolgun_allowed do
					toolgun_allowed[toolgun_allowed_key] = false
				end
				_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] All toolgunmodes have been deactivated")
				prop_send_text(userid,"All toolgunmodes have been deactivated")
			else
				for toolgun_allowed_key,toolgun_allowed_value in toolgun_allowed do
					toolgun_allowed[toolgun_allowed_key] = true
				end
				_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] All toolgunmodes have been activated")
				prop_send_text(userid,"All toolgunmodes have been activated")
			end
			resend_admin_panel()
		else
			if(arg == "" or toolgun_allowed[tonumber(arg)] == nil or tonumber(arg) == 22) then
				_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] Invalid toolgun mode - See list below and use the ID")
				show_toolgun_modes(userid,arg)
			else
				if(toolgun_allowed[tonumber(arg)] == true) then
					toolgun_allowed[tonumber(arg)] = false
					_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] Toolgunmode " .. toolgunmode_names[tonumber(arg)] .. " (" .. arg .. ") DEACTIVATED")
					prop_send_text(userid,"Toolgunmode " .. toolgunmode_names[tonumber(arg)] .. " has been deactivated")
				else
					toolgun_allowed[tonumber(arg)] = true
					_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] Toolgunmode " .. toolgunmode_names[tonumber(arg)] .. " (" .. arg .. ") ACTIVATED")
					prop_send_text(userid,"Toolgunmode " .. toolgunmode_names[tonumber(arg)] .. " has been activated")
				end
				resend_admin_panel()
				_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] Type \"toolgunlist\" to see all modes")
			end
		end
	else
		_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] You aren't allowed to use this command")
	end
end

CONCOMMAND("toolgundisable",disable_toolgun_mode)
CONCOMMAND("toolgunlist",show_toolgun_modes)

function prop_cleanupold(userid,arg)
	if(isAdmin(userid) == true) then
		-- delete props from old owners now or give old props to the new owner immediately
		for timeout_finished_key,timeout_finished_value in playerTimeoutTable do
			-- Remove the entities of this playerTimeoutTable
			remove_prop_now(timeout_finished_key)
		end
		-- Now cleanup stuff too, which noone owns like VMF loader stuff/vehicles and NPCs or copied and not physgunned stuff!
		local remover_table_oldents = {}
		remover_table_oldents[0] = {"prop_physics","prop_dynamic","phys_magnet","prop_door_rotating","prop_wheel"} -- Props
		remover_table_oldents[1] = {"prop_vehicle_airboat","prop_vehicle_jeep","prop_vehicle_prisoner_pod"} -- Vehicles
		remover_table_oldents[2] = {"prop_timedexplosion"} -- Dynamites
		remover_table_oldents[3] = {"hl2mp_ragdoll"} -- Player Corpses
		for remover_table_key,remover_table_value in remover_table_oldents do
			for props_key,props_value in remover_table_value do
				props = _EntitiesFindByClass(props_value)
				for k,v in props do
					if(cleanupTableEntitys[v] ~= nil) then
						if(playerGracetimeTable[cleanupTableEntitys[v]] ~= nil or playerTimeoutTable[cleanupTableEntitys[v]] ~= nil) then
							playerTimeoutTable[cleanupTableEntitys[v]] = _CurTime(); -- Timeout finished! - Remove the stuff now or give it to NewOwners
						end
					else
						if(_EntGetParent(v) == 0) then -- No ropes
							_EffectInit();
								_EffectSetOrigin( _EntGetPos( v ) );
								_EffectSetScale( 0.5 );
								_EffectSetMagnitude( 2 );
								_EffectSetRadius( 1 );
							_EffectDispatch( "cball_explode" );
							_EntRemove(v)
							-- Unsetting all needed tables
							entityGroup[v] = nil
							newOwnerTableEntitys[v] = nil
							cleanupTableEntitys[v] = nil
						end
					end
				end
			end
		end
		_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] Cleaned up all old props")
	else
		_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] You aren't allowed to use this command")
	end
end
CONCOMMAND("cleanupold",prop_cleanupold)

function prop_cleanup_mode(userid,arg)
	if(isAdmin(userid) == true) then
		if(arg ~= "") then
			-- All thinkable to remove for a proper cleanup of the whole map - Nearly new :D
			local remover_table = {}
			remover_table[0] = {"prop_physics","prop_dynamic","phys_magnet","prop_door_rotating","prop_wheel"} -- Props
			remover_table[1] = {"physics_balloon"} -- Balloons
			remover_table[2] = {"physics_thruster"} -- Thrusters
			remover_table[3] = {"prop_placement","env_sprite"} -- Sprites and effects
			remover_table[4] = {"prop_ragdoll"} -- Ragdolls
			remover_table[5] = {"func_physbox"} -- Physboxes
			remover_table[6] = {"keyframe_rope","move_rope","phys_slideconstraint","phys_pulleyconstraint","phys_lengthconstraint","phys_spring"} -- Ropes pulleys etc
			remover_table[7] = {"prop_emitter"} -- Emitters
			remover_table[8] = {"env_smoketrail"} -- Smoketrails
			remover_table[9] = {"env_fire_trail"} -- Firetrails
			remover_table[10] = {"env_flare"} -- Flares
			remover_table[11] = {"entityflame","env_fire"} -- Fires
			remover_table[12] = {"env_spark"} -- Sparklers
			remover_table[13] = {"prop_timedexplosion"} -- Dynamites
			remover_table[14] = {"Npc_alyx","Npc_antlion","Npc_antlion_template_maker","Npc_antlionguard","Npc_assassin","Npc_barnacle","Npc_barney",
			"Npc_bullseye","Npc_citizen","Npc_combine_camera","Npc_combine_s","Npc_combine","Npc_combine_e","Npc_combine_p","Npc_combinedropship",
			"Npc_combinegunship","Npc_crabsynth","Npc_crow","Npc_cscanner","Npc_dog","Npc_enemyfinder","Npc_fastzombie","Npc_fisherman",
			"Npc_furniture","Npc_headcrab","Npc_headcrab_black","Npc_headcrab_fast","Npc_heli_avoidbox","Npc_heli_avoidsphere","Npc_heli_nobomb",
			"Npc_helicopter","Npc_ichthyosaur","Npc_launcher","Npc_maker","Npc_manhack","Npc_metropolice","Npc_missiledefense","Npc_mortarsynth",
			"Npc_particlestorm","Npc_pigeon","Npc_poisonzombie","Npc_roller","Npc_rollerbuddy","Npc_rollerbull","Npc_rollerdozer","Npc_rollermine",
			"Npc_rollerturret","Npc_seagull","Npc_sniper","Npc_spotlight","Npc_sscanner","Npc_stalker","Npc_strider","Npc_template_maker",
			"Npc_turret_ceiling","Npc_turret_floor","Npc_turret_ground","Npc_vortigaunt","Npc_wscanner","Npc_zombie","Npc_zombie_torso"} -- NPCs
			remover_table[15] = {"prop_vehicle_airboat","prop_vehicle_jeep","prop_vehicle_prisoner_pod"} -- Vehicles
			remover_table[16] = {"item_ammo_357","item_ammo_ar2","item_ammo_ar2_altfire","item_ammo_crossbow","item_ammo_pistol",
			"item_rpg_round","item_healthcharger","item_healthkit","item_healthvial","item_suitcharger"} -- Ammo
			-- I don't want peoples weopons removed out of their hands ;D - but maybe you ;)
			remover_table[17] = {"weapon_357","weapon_ar2","weapon_crossbow","weapon_crowbar","weapon_frag","weapon_pistol","weapon_rpg","weapon_shotgun","weapon_slam","weapon_smg1","weapon_stunstick"}
			remover_table[18] = {"prop_combine_ball","func_combine_ball_spawner"} -- Combine Balls and Ballspawners
			remover_table[19] = {"env_beam","env_laser"} -- Beams
			remover_table[20] = {"phys_ragdollconstraint","phys_constraint"} -- Welds
			remover_table[21] = {"hl2mp_ragdoll"} -- Player Corpses
			local modelName = ""
			if(arg ~= "all") then
				for props_key,props_value in remover_table[tonumber(arg)] do
					props = _EntitiesFindByClass(props_value)
					for k,v in props do
						if(tostring(_EntGetParent(v)) == "0" or (tonumber(arg) ~= 17 and tonumber(arg) ~= 16)) then
							modelName = _EntGetModel(v);
							if((string.find(modelName,"*") == nil)) then -- Dont affect mapelements like brushes or inbuild doors (models included in map)
								_EffectInit();
									_EffectSetOrigin( _EntGetPos( v ) );
									_EffectSetScale( 0.5 );
									_EffectSetMagnitude( 2 );
									_EffectSetRadius( 1 );
								_EffectDispatch( "cball_explode" );
								_EntRemove(v)
								-- Unsetting all needed tables
								entityGroup[v] = nil
								newOwnerTableEntitys[v] = nil
								cleanupTableEntitys[v] = nil
							end
						end
					end
				end
				_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] Cleaned up the desired mode")
			else
				for remover_table_key,remover_table_value in remover_table do
					for props_key,props_value in remover_table_value do
						props = _EntitiesFindByClass(props_value)
						for k,v in props do
							if(tostring(_EntGetParent(v)) == "0" or (tonumber(remover_table_key) ~= 17 and tonumber(remover_table_key) ~= 16)) then
								if(string.find(modelName,"*") == nil) then -- Dont affect mapelements like brushes or inbuild doors (models included in map)
									_EffectInit();
										_EffectSetOrigin( _EntGetPos( v ) );
										_EffectSetScale( 0.5 );
										_EffectSetMagnitude( 2 );
										_EffectSetRadius( 1 );
									_EffectDispatch( "cball_explode" );
									_EntRemove(v)
									-- Unsetting all needed tables
									entityGroup[v] = nil
									newOwnerTableEntitys[v] = nil
									cleanupTableEntitys[v] = nil
								end
							end
						end
					end
				end
				_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] Cleaned up everything of the map")
			end
		end
	else
		_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] You aren't allowed to use this command")
	end
end
CONCOMMAND("cleanupmode",prop_cleanup_mode) -- This concommand is just used for the adminmenu - Maybe, i will add later an infodialog to it, like toolgunlist

function prop_cleanupall(userid,arg)
	prop_cleanup_mode(userid,"all")
end
CONCOMMAND("cleanupall",prop_cleanupall)

function prop_indicatepropstoggle(userid,arg)
	if(isAdmin(userid) == true) then
		if(indicate_prop == true) then
			indicate_prop = false
			_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] Propindication turned OFF")
			for cleanupTableEntitys_key,cleanupTableEntitys_value in cleanupTableEntitys do
				remove_indicator_from_prop(cleanupTableEntitys_key) -- Indication has been set off - Remove all indications now.
			end
		else
			indicate_prop = true
			_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] Propindication turned ON")
		end
		resend_admin_panel()
	else
		_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] You aren't allowed to use this command")
	end
end
CONCOMMAND("indicatepropstoggle",prop_indicatepropstoggle)

function prop_colorpropstoggle(userid,arg)
	if(isAdmin(userid) == true) then
		if(color_props == true) then
			color_props = false
			_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] Coloring old props turned OFF")
		else
			color_props = true
			_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] Coloring old props turned ON")
		end
		resend_admin_panel()
	else
		_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] You aren't allowed to use this command")
	end
end
CONCOMMAND("colorpropstoggle",prop_colorpropstoggle)

function prop_toolguntoggle(userid,arg)
	if(isAdmin(userid) == true) then
		if(allow_toolgun_on_all_props == true) then
			allow_toolgun_on_all_props = false
			_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] Toolgun just allowed on own props")
		else
			allow_toolgun_on_all_props = true
			_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] Toolgun allowed on every prop (no remover)")
		end
		resend_admin_panel()
	else
		_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] You aren't allowed to use this command")
	end
end
CONCOMMAND("toolguntoggle",prop_toolguntoggle)

function prop_proptexttoggle(userid,arg)
	if(isAdmin(userid) == true) then
		if(indicate_prop_text == true) then
			indicate_prop_text = false
			_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] Text on old props turned OFF")
			for cleanupTableEntitys_key,cleanupTableEntitys_value in cleanupTableEntitys do
				_GModText_Hide(0,4444 + cleanupTableEntitys_key) -- Remove texts from the entities now!
			end
		else
			indicate_prop_text = true
			_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] Text on old props turned ON")
		end
		resend_admin_panel()
	else
		_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] You aren't allowed to use this command")
	end
end
CONCOMMAND("proptexttoggle",prop_proptexttoggle)

function prop_autoremovetoggle(userid,arg)
	if(isAdmin(userid) == true) then
		if(autoremove_props == true) then
			autoremove_props = false
			_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] Autoremover turned OFF")
		else
			autoremove_props = true
			_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] Autoremover turned ON")
		end
		resend_admin_panel()
	else
		_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] You aren't allowed to use this command")
	end
end
CONCOMMAND("autoremovetoggle",prop_autoremovetoggle)

function prop_propprotectortoggle(userid,arg)
	if(isAdmin(userid) == true) then
		if(protect_props == true) then
			protect_props = false
			_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] PropProtector turned OFF")
		else
			protect_props = true
			_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] PropProtector turned ON")
		end
		resend_admin_panel()
	else
		_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] You aren't allowed to use this command")
	end
end
CONCOMMAND("propprotectortoggle",prop_propprotectortoggle)

function prop_disable_ownership_of_next_prop(userid,arg)
	_GModText_Hide(userid, 97)
	_GModText_Hide(userid, 99)
	_GModRect_Hide(userid, 405, 0, 0)
	_GModRect_Hide(userid, 406, 0.5, 0)
	if(freeNextProp[_PlayerInfoCompatibility(userid,"networkid")] == false) then
		_GModText_Start("CloseCaption_Bold")
		_GModText_SetPos(0.21, 0.25)
		_GModText_SetTime( 9999, 0, 0 )
		_GModText_SetColor( 255, 128, 0, 200 )
		_GModText_SetText( "The next prop, you use physgun on will be free for all!" )
		_GModText_SetDelay( 0 )
		_GModText_Send( userid, 99 )
		prop_message_rect( userid , 9999, 406, 0.15, 0.216)
		_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] The next prop, you use physgun on will be free for all")
		_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] Type \"freeprop\" again, to get back to normal gameplay")
		freeNextProp[_PlayerInfoCompatibility(userid,"networkid")] = true
	else
		_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] Propfreeing mode left")
		freeNextProp[_PlayerInfoCompatibility(userid,"networkid")] = false
	end
end
CONCOMMAND("freeprop",prop_disable_ownership_of_next_prop)

function prop_disable_ownership_of_next_prop_toggle(userid,arg)
	_GModText_Hide(userid, 97)
	_GModText_Hide(userid, 99)
	_GModRect_Hide(userid, 405, 0, 0)
	_GModRect_Hide(userid, 406, 0.5, 0)
	if(freeNextProp[_PlayerInfoCompatibility(userid,"networkid")] == false) then
		_GModText_Start("CloseCaption_Bold")
		_GModText_SetPos(0.21, 0.25)
		_GModText_SetTime( 9999, 0, 0 )
		_GModText_SetColor( 255, 0, 0, 200 )
		_GModText_SetText( "The next props, you use physgun on will be free for all!\nTurn off this togglemode by typing \"freeproptoggle\" again" )
		_GModText_SetDelay( 0 )
		_GModText_Send( userid, 97 )
		prop_message_rect( userid , 9999, 405, 0.15,0.236)
		_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] The next props, you use physgun on will be free for all - Attention - This is the togglemode!")
		_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] Type \"freeproptoggle\" again, to get back to normal gameplay")
		freeNextProp[_PlayerInfoCompatibility(userid,"networkid")] = 2
	else
		_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] Propfreeing mode left")
		freeNextProp[_PlayerInfoCompatibility(userid,"networkid")] = false
	end
end
CONCOMMAND("freeproptoggle",prop_disable_ownership_of_next_prop_toggle)

function prop_showhelp(userid,arg)
	_PrintMessage(userid,HUD_PRINTCONSOLE,"      [PROP] All PropProtector console commands")
	_PrintMessage(userid,HUD_PRINTCONSOLE,"-User commands")
	
	_PrintMessage(userid,HUD_PRINTCONSOLE,"joingroup <username> - join a players group")
	_PrintMessage(userid,HUD_PRINTCONSOLE,"leavegroup - leave a group")
	_PrintMessage(userid,HUD_PRINTCONSOLE,"toolgunlist - shows all toolgunmodes and their status")
	
	if(isAdmin(userid) == true) then
		_PrintMessage(userid,HUD_PRINTCONSOLE,"-Admin commands")
		
		_PrintMessage(userid,HUD_PRINTCONSOLE,"toolgundisable <id> - turnes off a toolgunmode - get the id with \"toolgunlist\"")
		_PrintMessage(userid,HUD_PRINTCONSOLE,"indicatepropstoggle - turnes off/on indication on old props")
		_PrintMessage(userid,HUD_PRINTCONSOLE,"proptexttoggle - turnes off/on textindication on old props")
		_PrintMessage(userid,HUD_PRINTCONSOLE,"colorpropstoggle - turnes off/on coloring old props")
		_PrintMessage(userid,HUD_PRINTCONSOLE,"cleanupold - removes all old props of left players")
		_PrintMessage(userid,HUD_PRINTCONSOLE,"cleanupall - removes ALL props from server")
		_PrintMessage(userid,HUD_PRINTCONSOLE,"autoremovetoggle - turnes off/on the autoremover")
		_PrintMessage(userid,HUD_PRINTCONSOLE,"propprotectortoggle - turnes off/on the protectionmode")
		_PrintMessage(userid,HUD_PRINTCONSOLE,"freeprop - next physgunned prop you own, will be freed - anyone can use then")
		_PrintMessage(userid,HUD_PRINTCONSOLE,"freeproptoggle - all physgunned prop will be free for all - disable toggle mode by typing this again")
		_PrintMessage(userid,HUD_PRINTCONSOLE,"freeallmyprops - makes all your props free for all (vote before)")
		_PrintMessage(userid,HUD_PRINTCONSOLE,"removemyprops - removes all your props (vote before)")
	end
end
CONCOMMAND("prop_help",prop_showhelp)

-- Free all the users props now
function freeallmyprops_vote(userid, num, seconds)
	_GModRect_Hide(userid, 401, 0.5, 0)
	_GModText_Hide(userid, 402, 0.5, 0)
	_GModText_Hide(userid, 403, 0.5, 0)
	if(num == 1) then
		for remove_key,remove_value in cleanupTableEntitys do
			if(remove_value == _PlayerInfoCompatibility(userid,"networkid")) then
				remove_indicator_from_prop(remove_key) -- Unset flags for old props
				cleanupTableEntitys[remove_key] = nil
				entityGroup[remove_key] = nil
			end
		end
		prop_send_text(userid,"You left the ownershipt of all your props!")
	else
		prop_send_text(userid,"You haven't left ownershipt of you props!")
	end
end

-- Concommand for the freeall my props function
function prop_freeallmyprops(userid,arg)
	PropPlayerMenu(userid,"Give up ownership\nof all your props?","freeallmyprops_vote")
end
CONCOMMAND("freeallmyprops",prop_freeallmyprops)

-- Remove all the users props now
function removemyprops_vote(userid, num, seconds)
	local del_prop = false;
	local ent_type = "";
	_GModRect_Hide(userid, 401, 0.5, 0)
	_GModText_Hide(userid, 402, 0.5, 0)
	_GModText_Hide(userid, 403, 0.5, 0)
	local ppremover_table = {}
	ppremover_table[1] = {"prop_physics","prop_dynamic"}
	ppremover_table[2] = {"prop_vehicle_jeep","prop_vehicle_airboat","prop_vehicle_prisoner_pod"}
	ppremover_table[3] = {"physics_thruster"}
	ppremover_table[4] = {"prop_wheel"}
	ppremover_table[5] = {"prop_timedexplosion"}
	ppremover_table[6] = {"physics_balloon"}
	if(num == 1) then
		for remove_key,remove_value in cleanupTableEntitys do
			if(remove_value == _PlayerInfoCompatibility(userid,"networkid")) then
				if(player_remove_stuff_mode[userid] ~= 0) then
					del_prop = false;
					ent_type = _EntGetType(remove_key);
					for k,v in ppremover_table[player_remove_stuff_mode[userid]] do
						if(v == ent_type) then
							del_prop = true;
							break;
						end
					end
				else
					del_prop = true;
				end
				if(del_prop == true) then
					remove_indicator_from_prop(remove_key) -- Unset flags for old props
					_EffectInit();
						_EffectSetOrigin( _EntGetPos( remove_key ) );
						_EffectSetScale( 0.5 );
						_EffectSetMagnitude( 2 );
						_EffectSetRadius( 1 );
					_EffectDispatch( "cball_explode" );
					_EntRemove(remove_key)
					cleanupTableEntitys[remove_key] = nil
					entityGroup[remove_key] = nil
				end
			end
		end
		prop_send_text(userid,"Specific Entities removed!")
	else
		prop_send_text(userid,"Nothing got removed!")
	end
end

--Command for remove all my props

function prop_removemyprops(userid,arg)
	if(arg == "all") then
		player_remove_stuff_mode[userid] = 0;
		PropPlayerMenu(userid,"Remove everything you spawned?","removemyprops_vote")
	else
		player_remove_stuff_mode[userid] = tonumber(arg);
		local ppremover_table_topic = {"props","vehicles","thrusters","wheels","dynamites","balloons"}
		PropPlayerMenu(userid,"Remove all your ".. ppremover_table_topic[tonumber(arg)].."?","removemyprops_vote")
	end
end
CONCOMMAND("removemyprops",prop_removemyprops)

function ppcgremovepattern_vote(userid, num, seconds)
	_GModRect_Hide(userid, 401, 0.5, 0)
	_GModText_Hide(userid, 402, 0.5, 0)
	_GModText_Hide(userid, 403, 0.5, 0)
	local cgremover_table = cgSpawnedStuff[_PlayerInfoCompatibility(userid, "networkid")][user_remove_cg_pattern_mode[userid]];
	local user_networkid = _PlayerInfoCompatibility(userid, "networkid");
	if(num == 1) then
		for k,v in cgremover_table do
			if(cleanupTableEntitys[v] == user_networkid) then
				unColorEnt(v) -- Unset flags for old props
				_EffectInit();
					_EffectSetOrigin( _EntGetPos( v ) );
					_EffectSetScale( 0.5 );
					_EffectSetMagnitude( 2 );
					_EffectSetRadius( 1 );
				_EffectDispatch( "cball_explode" );
				_EntRemove(v)
				cleanupTableEntitys[v] = nil
				entityGroup[v] = nil
			end
		end
		local new_cg_spawned_table = {}
		for k,v in cgSpawnedStuff[_PlayerInfoCompatibility(userid, "networkid")] do
			if(k ~= user_remove_cg_pattern_mode[userid]) then
				new_cg_spawned_table[table.getn(new_cg_spawned_table)+1] = v;
			end
		end
		cgSpawnedStuff[_PlayerInfoCompatibility(userid, "networkid")] = new_cg_spawned_table;
		-- And resend the panel now#
		setSpawnmenu_propmanager(userid)
	else
		for k,v in cgremover_table do
			if(cleanupTableEntitys[v] == user_networkid) then
				unColorEnt(v);
			end
		end
	end
end

user_remove_cg_pattern_mode = {};
function prop_removecgpattern(userid, arg)
	user_remove_cg_pattern_mode[userid] = tonumber(arg);
	local cgremover_table = cgSpawnedStuff[_PlayerInfoCompatibility(userid, "networkid")][tonumber(arg)];
	for k,v in cgremover_table do
		colorEnt(v);
	end
	PropPlayerMenu(userid,"Remove CopyGun Pattern No. ".. tonumber(arg).."?","ppcgremovepattern_vote");
end

CONCOMMAND("ppcgremovepattern", prop_removecgpattern);

function resend_admin_panel()
	for i=1, _MaxPlayers() do
		if(_PlayerInfoCompatibility(i,"connected")) then
			if(isAdmin(i) == true) then
				--Resend the adminpanel to Admins
				setSpawnmenu_adminpanel(i)
			end
		end
	end
end

function PropPlayerChoose(userid, num, seconds)
	-- Hide menu
	_GModRect_Hide(userid, 401, 0.5, 0)
	_GModText_Hide(userid, 402, 0.5, 0)
	_GModText_Hide(userid, 403, 0.5, 0)
	if(num == 1) then
		-- Add a vote
		playerGroupsVotes[playerGroups[_PlayerInfoCompatibility(userid,"networkid")]] = 1 + playerGroupsVotes[playerGroups[_PlayerInfoCompatibility(userid,"networkid")]] -- Add a vote
		vote_answer = "YES"
	else
		vote_answer = "NO"
	end
	-- Send this answer to the person, who voted for a joinvote
	_PrintMessage(playerGroupsVotePlayer[playerGroups[_PlayerInfoCompatibility(userid,"networkid")]],HUD_PRINTTALK,"[PROP] " .. _PlayerInfoCompatibility(userid,"name") .. " voted " .. vote_answer)
	-- And now, send the answer to all people in the group
	for ix=1, _MaxPlayers() do
		if(_PlayerInfoCompatibility(ix,"connected")) then
			if(playerGroups[_PlayerInfoCompatibility(ix,"networkid")] == playerGroups[_PlayerInfoCompatibility(userid,"networkid")]) then
				_PrintMessage(ix,HUD_PRINTTALK,"[PROP] " .. _PlayerInfoCompatibility(userid,"name") .. " voted " .. vote_answer)
			end
		end
	end
end

-- Standard Rect, which appears behind messages
function prop_message_rect(userid,duration,rec_id,rx,ry)
	if(rec_id == nil) then
		rec_id = 404
	end
	if(rx == nil or ry == nil) then
		rx = 0.15
		ry = 0.365
	end
	_GModRect_Hide(userid, 404, 0 , 0)
	_GModRect_Start("gmod/white")
	_GModRect_SetPos(rx, ry, 0.7, 0.10)
	_GModRect_SetColor(0, 0, 0, 150)
	_GModRect_SetTime(duration - 0.5, 0, 0.5)
	_GModRect_Send(userid, rec_id)
end

function PropPlayerMenu(userid,topic,vote_function)
	_GModRect_Start("gmod/white")
	_GModRect_SetPos(0.03, 0.3, 0.32, 0.32)
	_GModRect_SetColor(0, 0, 0, 150)
	_GModRect_SetTime(vote_timeout, 0.5, 0.5)
	_GModRect_Send(userid, 401)
	
	-- Vote Topic
	_GModText_Start("CloseCaption_Bold")
	_GModText_SetPos(0.04, 0.315)
	_GModText_SetTime(vote_timeout, 1, 0.5)
	_GModText_SetText(topic)
	_GModText_SetColor(255, 200, 50, 255)
	_GModText_Send(userid, 402)
	
	-- Vote Answers
	_GModText_Start("ChatFont")
	_GModText_SetPos(0.05, 0.4)
	_GModText_SetTime(vote_timeout, 1, 0.5)
	_GModText_SetText("1. Yes\n2. No")
	_GModText_SetColor(255, 255, 255, 255)
	_GModText_Send(userid, 403)
	
	_PlayerOption(userid, vote_function, vote_timeout)
end
