#include maps\mp\gametypes\_weapons;

limiter_init()
{
	level endon("ex_gameover");

	level thread limitUpdate();

	for(;;)
	{
		countPlayerWeapons();
		wait 0.05;
	}
}

countPlayerWeapons()
{
	for(i = 0; i < level.ex_wlim_names.size; i++)
	{
		weapon = level.ex_wlim_names[i];
		count = 0;

		// get the players array
		players = getentarray("player", "classname");

		// reset the weapon, if there are no players (stock routine)
		if(players.size < 1)
		{
			level updateAllowed();
			wait 4.5;
			return;
		}

		for(j = 0; j < players.size; j++)
		{
			player = players[j];

			// don't count real spectators
			if(isPlayer(player) && isDefined(player.pers["team"]) && player.pers["team"] == "spectator") continue;

			// check players that are not spectator team and have not started playing, i.e. just joined or switched sides
			if(isPlayer(player) && player.sessionstate == "spectator")
			{
				// check for a primary being chosen, primaryb (secondary) is not checked now, cause they will have spawned directly after choosing
				if(isDefined(player.pers["weapon"]) && weapon == player.pers["weapon"]) count++;
			}
			else if(isPlayer(player) && isDefined(player.weapon["primary"].name))
			{
				if(weapon == player.weapon["primary"].name) count++;
				else if(weapon == player.weapon["primaryb"].name) count++;
				else if(weapon == player.weapon["virtual"].name) count++;
				else if(weapon == "fraggrenade") count = player getFragGrenadeCount();
				else if(weapon == "smokegrenade") count = player getSmokeGrenadeCount();
				else if(weapon == "binoculars_mp") count = player getBinocularCount();
			}
		}

		if(count >= level.weapons[weapon].limit) level.weapons[weapon].cvarvalue = 0;
			else level.weapons[weapon].cvarvalue = 1;
	}
}

limitUpdate()
{
	level endon("ex_gameover");

	for(;;)
	{
		wait 0.05;

		for(i = 0; i < level.ex_wlim_names.size; i++)
		{
			weapon = level.ex_wlim_names[i];
			
			if(level.weapons[weapon].allow != level.weapons[weapon].cvarvalue)
			{
				level.weapons[weapon].allow = level.weapons[weapon].cvarvalue;
				level thread updateAllowedSinglelClients(weapon);
			}
		}
	}
}
