]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blobdiff - qcsrc/server/teamplay.qc
Better team balance function names.
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / teamplay.qc
index c991f72ec7e6ad93affd4c4519367846bb88d54f..aa2a44b2920e41165fad693e2a676294cf3fa0e9 100644 (file)
 #include "../common/gamemodes/_mod.qh"
 #include "../common/teams.qh"
 
+/// \brief Indicates that the player is not allowed to join a team.
+const int TEAM_NOT_ALLOWED = -1;
+
+.float m_team_score; ///< The score of the team.
+.int m_num_players; ///< Number of players (both humans and bots) in a team.
+.int m_num_bots; ///< Number of bots in a team.
+.entity m_lowest_human; ///< Human with the lowest score in a team.
+.entity m_lowest_bot; ///< Bot with the lowest score in a team.
+
+entity g_team_entities[4]; ///< Holds global team entities.
+
+STATIC_INIT(g_team_entities)
+{
+       g_team_entities[0] = spawn();
+       g_team_entities[1] = spawn();
+       g_team_entities[2] = spawn();
+       g_team_entities[3] = spawn();
+}
+
+entity Team_GetTeamFromIndex(int index)
+{
+       if (!Team_IsValidIndex(index))
+       {
+               LOG_FATALF("Team_GetTeamFromIndex: Index is invalid: %f", index);
+       }
+       return g_team_entities[index - 1];
+}
+
+entity Team_GetTeam(int team_num)
+{
+       if (!Team_IsValidTeam(team_num))
+       {
+               LOG_FATALF("Team_GetTeam: Value is invalid: %f", team_num);
+       }
+       return g_team_entities[Team_TeamToNumber(team_num) - 1];
+}
+
+float Team_GetTeamScore(entity team_)
+{
+       return team_.m_team_score;
+}
+
+void Team_SetTeamScore(entity team_, float score)
+{
+       team_.m_team_score = score;
+}
+
+void CheckAllowedTeams(entity for_whom)
+{
+       for (int i = 0; i < 4; ++i)
+       {
+               g_team_entities[i].m_num_players = TEAM_NOT_ALLOWED;
+               g_team_entities[i].m_num_bots = 0;
+               g_team_entities[i].m_lowest_human = NULL;
+               g_team_entities[i].m_lowest_bot = NULL;
+       }
+       
+       int teams_mask = 0;     
+       string teament_name = string_null;
+       bool mutator_returnvalue = MUTATOR_CALLHOOK(CheckAllowedTeams, teams_mask,
+               teament_name, for_whom);
+       teams_mask = M_ARGV(0, float);
+       teament_name = M_ARGV(1, string);
+       if (mutator_returnvalue)
+       {
+               for (int i = 0; i < 4; ++i)
+               {
+                       if (teams_mask & BIT(i))
+                       {
+                               g_team_entities[i].m_num_players = 0;
+                       }
+               }
+       }
+
+       // find out what teams are allowed if necessary
+       if (teament_name)
+       {
+               entity head = find(NULL, classname, teament_name);
+               while (head)
+               {
+                       if (Team_IsValidTeam(head.team))
+                       {
+                               Team_GetTeam(head.team).m_num_players = 0;
+                       }
+                       head = find(head, classname, teament_name);
+               }
+       }
+
+       // TODO: Balance quantity of bots across > 2 teams when bot_vs_human is set (and remove next line)
+       if (AvailableTeams() == 2)
+       if (autocvar_bot_vs_human && for_whom)
+       {
+               if (autocvar_bot_vs_human > 0)
+               {
+                       // find last team available
+                       if (IS_BOT_CLIENT(for_whom))
+                       {
+                               if (Team_IsAllowed(g_team_entities[3]))
+                               {
+                                       g_team_entities[2].m_num_players = TEAM_NOT_ALLOWED;
+                                       g_team_entities[1].m_num_players = TEAM_NOT_ALLOWED;
+                                       g_team_entities[0].m_num_players = TEAM_NOT_ALLOWED;
+                               }
+                               else if (Team_IsAllowed(g_team_entities[2]))
+                               {
+                                       g_team_entities[3].m_num_players = TEAM_NOT_ALLOWED;
+                                       g_team_entities[1].m_num_players = TEAM_NOT_ALLOWED;
+                                       g_team_entities[0].m_num_players = TEAM_NOT_ALLOWED;
+                               }
+                               else
+                               {
+                                       g_team_entities[3].m_num_players = TEAM_NOT_ALLOWED;
+                                       g_team_entities[2].m_num_players = TEAM_NOT_ALLOWED;
+                                       g_team_entities[0].m_num_players = TEAM_NOT_ALLOWED;
+                               }
+                               // no further cases, we know at least 2 teams exist
+                       }
+                       else
+                       {
+                               if (Team_IsAllowed(g_team_entities[0]))
+                               {
+                                       g_team_entities[1].m_num_players = TEAM_NOT_ALLOWED;
+                                       g_team_entities[2].m_num_players = TEAM_NOT_ALLOWED;
+                                       g_team_entities[3].m_num_players = TEAM_NOT_ALLOWED;
+                               }
+                               else if (Team_IsAllowed(g_team_entities[1]))
+                               {
+                                       g_team_entities[0].m_num_players = TEAM_NOT_ALLOWED;
+                                       g_team_entities[2].m_num_players = TEAM_NOT_ALLOWED;
+                                       g_team_entities[3].m_num_players = TEAM_NOT_ALLOWED;
+                               }
+                               else
+                               {
+                                       g_team_entities[0].m_num_players = TEAM_NOT_ALLOWED;
+                                       g_team_entities[1].m_num_players = TEAM_NOT_ALLOWED;
+                                       g_team_entities[3].m_num_players = TEAM_NOT_ALLOWED;
+                               }
+                               // no further cases, bots have one of the teams
+                       }
+               }
+               else
+               {
+                       // find first team available
+                       if (IS_BOT_CLIENT(for_whom))
+                       {
+                               if (Team_IsAllowed(g_team_entities[0]))
+                               {
+                                       g_team_entities[1].m_num_players = TEAM_NOT_ALLOWED;
+                                       g_team_entities[2].m_num_players = TEAM_NOT_ALLOWED;
+                                       g_team_entities[3].m_num_players = TEAM_NOT_ALLOWED;
+                               }
+                               else if (Team_IsAllowed(g_team_entities[1]))
+                               {
+                                       g_team_entities[0].m_num_players = TEAM_NOT_ALLOWED;
+                                       g_team_entities[2].m_num_players = TEAM_NOT_ALLOWED;
+                                       g_team_entities[3].m_num_players = TEAM_NOT_ALLOWED;
+                               }
+                               else
+                               {
+                                       g_team_entities[0].m_num_players = TEAM_NOT_ALLOWED;
+                                       g_team_entities[1].m_num_players = TEAM_NOT_ALLOWED;
+                                       g_team_entities[3].m_num_players = TEAM_NOT_ALLOWED;
+                               }
+                               // no further cases, we know at least 2 teams exist
+                       }
+                       else
+                       {
+                               if (Team_IsAllowed(g_team_entities[3]))
+                               {
+                                       g_team_entities[2].m_num_players = TEAM_NOT_ALLOWED;
+                                       g_team_entities[1].m_num_players = TEAM_NOT_ALLOWED;
+                                       g_team_entities[0].m_num_players = TEAM_NOT_ALLOWED;
+                               }
+                               else if (Team_IsAllowed(g_team_entities[2]))
+                               {
+                                       g_team_entities[3].m_num_players = TEAM_NOT_ALLOWED;
+                                       g_team_entities[1].m_num_players = TEAM_NOT_ALLOWED;
+                                       g_team_entities[0].m_num_players = TEAM_NOT_ALLOWED;
+                               }
+                               else
+                               {
+                                       g_team_entities[3].m_num_players = TEAM_NOT_ALLOWED;
+                                       g_team_entities[2].m_num_players = TEAM_NOT_ALLOWED;
+                                       g_team_entities[0].m_num_players = TEAM_NOT_ALLOWED;
+                               }
+                               // no further cases, bots have one of the teams
+                       }
+               }
+       }
+
+       if (!for_whom)
+       {
+               return;
+       }
+
+       // if player has a forced team, ONLY allow that one
+       if (for_whom.team_forced == NUM_TEAM_1 && Team_IsAllowed(
+               g_team_entities[0]))
+       {
+               g_team_entities[1].m_num_players = TEAM_NOT_ALLOWED;
+               g_team_entities[2].m_num_players = TEAM_NOT_ALLOWED;
+               g_team_entities[3].m_num_players = TEAM_NOT_ALLOWED;
+       }
+       else if (for_whom.team_forced == NUM_TEAM_2 && Team_IsAllowed(
+               g_team_entities[1]))
+       {
+               g_team_entities[0].m_num_players = TEAM_NOT_ALLOWED;
+               g_team_entities[2].m_num_players = TEAM_NOT_ALLOWED;
+               g_team_entities[3].m_num_players = TEAM_NOT_ALLOWED;
+       }
+       else if (for_whom.team_forced == NUM_TEAM_3 && Team_IsAllowed(
+               g_team_entities[2]))
+       {
+               g_team_entities[0].m_num_players = TEAM_NOT_ALLOWED;
+               g_team_entities[1].m_num_players = TEAM_NOT_ALLOWED;
+               g_team_entities[3].m_num_players = TEAM_NOT_ALLOWED;
+       }
+       else if (for_whom.team_forced == NUM_TEAM_4 && Team_IsAllowed(
+               g_team_entities[3]))
+       {
+               g_team_entities[0].m_num_players = TEAM_NOT_ALLOWED;
+               g_team_entities[1].m_num_players = TEAM_NOT_ALLOWED;
+               g_team_entities[2].m_num_players = TEAM_NOT_ALLOWED;
+       }
+}
+
+int GetAllowedTeams()
+{
+       int result = 0;
+       for (int i = 0; i < 4; ++i)
+       {
+               if (Team_IsAllowed(g_team_entities[i]))
+               {
+                       result |= BIT(i);
+               }
+       }
+       return result;
+}
+
+bool Team_IsAllowed(entity team_)
+{
+       return team_.m_num_players != TEAM_NOT_ALLOWED;
+}
+
+void GetTeamCounts(entity ignore)
+{
+       if (MUTATOR_CALLHOOK(GetTeamCounts) == true)
+       {
+               // Mutator has overriden the configuration.
+               for (int i = 0; i < 4; ++i)
+               {
+                       entity team_ = g_team_entities[i];
+                       if (Team_IsAllowed(team_))
+                       {
+                               MUTATOR_CALLHOOK(GetTeamCount, Team_NumberToTeam(i + 1), ignore,
+                                       team_.m_num_players, team_.m_num_bots, team_.m_lowest_human,
+                                       team_.m_lowest_bot);
+                               team_.m_num_players = M_ARGV(2, float);
+                               team_.m_num_bots = M_ARGV(3, float);
+                               team_.m_lowest_human = M_ARGV(4, entity);
+                               team_.m_lowest_bot = M_ARGV(5, entity);
+                       }
+               }
+       }
+       else
+       {
+               // Manually count all players.
+               FOREACH_CLIENT(true,
+               {
+                       if (it == ignore)
+                       {
+                               continue;
+                       }
+                       int team_num;
+                       if (IS_PLAYER(it) || it.caplayer)
+                       {
+                               team_num = it.team;
+                       }
+                       else if (it.team_forced > 0)
+                       {
+                               team_num = it.team_forced; // reserve the spot
+                       }
+                       else
+                       {
+                               continue;
+                       }
+                       if (!Team_IsValidTeam(team_num))
+                       {
+                               continue;
+                       }
+                       entity team_ = Team_GetTeam(team_num);
+                       if (!Team_IsAllowed(team_))
+                       {
+                               continue;
+                       }
+                       ++team_.m_num_players;
+                       if (IS_BOT_CLIENT(it))
+                       {
+                               ++team_.m_num_bots;
+                       }
+                       float temp_score = PlayerScore_Get(it, SP_SCORE);
+                       if (!IS_BOT_CLIENT(it))
+                       {
+                               if (team_.m_lowest_human == NULL)
+                               {
+                                       team_.m_lowest_human = it;
+                                       continue;
+                               }
+                               if (temp_score < PlayerScore_Get(team_.m_lowest_human,
+                                       SP_SCORE))
+                               {
+                                       team_.m_lowest_human = it;
+                               }
+                               continue;
+                       }
+                       if (team_.m_lowest_bot == NULL)
+                       {
+                               team_.m_lowest_bot = it;
+                               continue;
+                       }
+                       if (temp_score < PlayerScore_Get(team_.m_lowest_bot, SP_SCORE))
+                       {
+                               team_.m_lowest_bot = it;
+                       }
+               });
+       }
+
+       // if the player who has a forced team has not joined yet, reserve the spot
+       if (autocvar_g_campaign)
+       {
+               if (Team_IsValidIndex(autocvar_g_campaign_forceteam))
+               {
+                       entity team_ = Team_GetTeamFromIndex(autocvar_g_campaign_forceteam);
+                       if (team_.m_num_players == team_.m_num_bots)
+                       {
+                               ++team_.m_num_players;
+                       }
+               }
+       }
+}
+
+int Team_GetNumberOfPlayers(entity team_)
+{
+       return team_.m_num_players;
+}
+
+int Team_GetNumberOfBots(entity team_)
+{
+       return team_.m_num_bots;
+}
+
+entity Team_GetLowestHuman(entity team_)
+{
+       return team_.m_lowest_human;
+}
+
+entity Team_GetLowestBot(entity team_)
+{
+       return team_.m_lowest_bot;
+}
+
 void TeamchangeFrags(entity e)
 {
        PlayerScore_Clear(e);
@@ -37,21 +398,20 @@ void default_delayedinit(entity this)
                ScoreRules_generic();
 }
 
-void ActivateTeamplay()
-{
-       serverflags |= SERVERFLAG_TEAMPLAY;
-       teamplay = 1;
-       cvar_set("teamplay", "2");  // DP needs this for sending proper getstatus replies.
-}
-
 void InitGameplayMode()
 {
        VoteReset();
 
        // find out good world mins/maxs bounds, either the static bounds found by looking for solid, or the mapinfo specified bounds
        get_mi_min_max(1);
-       world.mins = mi_min;
-       world.maxs = mi_max;
+       // assign reflectively to avoid "assignment to world" warning
+       int done = 0; for (int i = 0, n = numentityfields(); i < n; ++i) {
+           string k = entityfieldname(i); vector v = (k == "mins") ? mi_min : (k == "maxs") ? mi_max : '0 0 0';
+           if (v) {
+            putentityfieldstring(i, world, sprintf("%v", v));
+            if (++done == 2) break;
+        }
+       }
        // currently, NetRadiant's limit is 131072 qu for each side
        // distance from one corner of a 131072qu cube to the opposite corner is approx. 227023 qu
        // set the distance according to map size but don't go over the limit to avoid issues with float precision
@@ -59,13 +419,11 @@ void InitGameplayMode()
        max_shot_distance = min(230000, vlen(world.maxs - world.mins));
 
        MapInfo_LoadMapSettings(mapname);
-       serverflags &= ~SERVERFLAG_TEAMPLAY;
-       teamplay = 0;
-       cvar_set("teamplay", "0");  // DP needs this for sending proper getstatus replies.
+       GameRules_teams(false);
 
        if (!cvar_value_issafe(world.fog))
        {
-               LOG_INFO("The current map contains a potentially harmful fog setting, ignored\n");
+               LOG_INFO("The current map contains a potentially harmful fog setting, ignored");
                world.fog = string_null;
        }
        if(MapInfo_Map_fog != "")
@@ -87,8 +445,8 @@ void InitGameplayMode()
 
 string GetClientVersionMessage(entity this)
 {
-       if (this.version_mismatch) {
-               if(this.version < autocvar_gameversion) {
+       if (CS(this).version_mismatch) {
+               if(CS(this).version < autocvar_gameversion) {
                        return strcat("This is Xonotic ", autocvar_g_xonoticversion,
                                "\n^3Your client version is outdated.\n\n\n### YOU WON'T BE ABLE TO PLAY ON THIS SERVER ###\n\n\nPlease update!!!^8");
                } else {
@@ -183,616 +541,305 @@ void SetPlayerColors(entity player, float _color)
        }
 }
 
-bool SetPlayerTeamSimple(entity player, int teamnum)
+void KillPlayerForTeamChange(entity player)
 {
-       if (player.team == teamnum)
+       if (IS_DEAD(player))
+       {
+               return;
+       }
+       if (MUTATOR_CALLHOOK(Player_ChangeTeamKill, player) == true)
+       {
+               return;
+       }
+       Damage(player, player, player, 100000, DEATH_TEAMCHANGE.m_id, DMG_NOWEP,
+               player.origin, '0 0 0');
+}
+
+bool SetPlayerTeamSimple(entity player, int team_num)
+{
+       if (player.team == team_num)
        {
                // This is important when players join the game and one of their color
                // matches the team color while other doesn't. For example [BOT]Lion.
-               SetPlayerColors(player, teamnum - 1);
+               SetPlayerColors(player, team_num - 1);
                return true;
        }
        if (MUTATOR_CALLHOOK(Player_ChangeTeam, player, Team_TeamToNumber(
-               player.team), Team_TeamToNumber(teamnum)) == true)
+               player.team), Team_TeamToNumber(team_num)) == true)
        {
                // Mutator has blocked team change.
                return false;
        }
-       int oldteam = player.team;
-       SetPlayerColors(player, teamnum - 1);
-       MUTATOR_CALLHOOK(Player_ChangedTeam, player, oldteam, player.team);
+       int old_team_num = player.team;
+       SetPlayerColors(player, team_num - 1);
+       MUTATOR_CALLHOOK(Player_ChangedTeam, player, old_team_num, player.team);
        return true;
 }
 
-void SetPlayerTeam(entity player, int destinationteam, int sourceteam, bool noprint)
+bool SetPlayerTeam(entity player, int destination_team_index,
+       int source_team_index, bool no_print)
 {
-       int teamnum = Team_NumberToTeam(destinationteam);
-       if (!SetPlayerTeamSimple(player, teamnum))
+       int team_num = Team_NumberToTeam(destination_team_index);
+       if (!SetPlayerTeamSimple(player, team_num))
        {
-               return;
+               return false;
        }
        LogTeamchange(player.playerid, player.team, 3);  // log manual team join
-       if (noprint)
+       if (no_print)
        {
-               return;
+               return true;
        }
-       bprint(playername(player, false), "^7 has changed from ", Team_NumberToColoredFullName(sourceteam), "^7 to ", Team_NumberToColoredFullName(destinationteam), "\n");
+       bprint(playername(player, false), "^7 has changed from ",
+               Team_NumberToColoredFullName(source_team_index), "^7 to ",
+               Team_NumberToColoredFullName(destination_team_index), "\n");
+       return true;
 }
 
-// set c1...c4 to show what teams are allowed
-void CheckAllowedTeams (entity for_whom)
+int FindBestTeamsForBalance(entity player, bool use_score)
 {
-       int teams_mask = 0;
-
-       c1 = c2 = c3 = c4 = -1;
-       numbotsteam1 = numbotsteam2 = numbotsteam3 = numbotsteam4 = 0;
-
-       string teament_name = string_null;
-
-       bool mutator_returnvalue = MUTATOR_CALLHOOK(CheckAllowedTeams, teams_mask, teament_name, for_whom);
-       teams_mask = M_ARGV(0, float);
-       teament_name = M_ARGV(1, string);
-
-       if(!mutator_returnvalue)
+       if (MUTATOR_CALLHOOK(FindBestTeams, player) == true)
        {
-               if(teams_mask & BIT(0)) c1 = 0;
-               if(teams_mask & BIT(1)) c2 = 0;
-               if(teams_mask & BIT(2)) c3 = 0;
-               if(teams_mask & BIT(3)) c4 = 0;
+               return M_ARGV(1, float);
        }
-
-       // find out what teams are allowed if necessary
-       if(teament_name)
+       int team_bits = 0;
+       int previous_team = 0;
+       if (Team_IsAllowed(g_team_entities[0]))
        {
-               entity head = find(NULL, classname, teament_name);
-               while(head)
-               {
-                       switch(head.team)
-                       {
-                               case NUM_TEAM_1: c1 = 0; break;
-                               case NUM_TEAM_2: c2 = 0; break;
-                               case NUM_TEAM_3: c3 = 0; break;
-                               case NUM_TEAM_4: c4 = 0; break;
-                       }
-
-                       head = find(head, classname, teament_name);
-               }
+               team_bits = BIT(0);
+               previous_team = 1;
        }
-
-       // TODO: Balance quantity of bots across > 2 teams when bot_vs_human is set (and remove next line)
-       if(AvailableTeams() == 2)
-       if(autocvar_bot_vs_human && for_whom)
+       if (Team_IsAllowed(g_team_entities[1]))
        {
-               if(autocvar_bot_vs_human > 0)
+               if (previous_team == 0)
                {
-                       // find last team available
-
-                       if(IS_BOT_CLIENT(for_whom))
-                       {
-                               if(c4 >= 0) { c3 = c2 = c1 = -1; }
-                               else if(c3 >= 0) { c4 = c2 = c1 = -1; }
-                               else { c4 = c3 = c1 = -1; }
-                               // no further cases, we know at least 2 teams exist
-                       }
-                       else
-                       {
-                               if(c1 >= 0) { c2 = c3 = c4 = -1; }
-                               else if(c2 >= 0) { c1 = c3 = c4 = -1; }
-                               else { c1 = c2 = c4 = -1; }
-                               // no further cases, bots have one of the teams
-                       }
+                       team_bits = BIT(1);
+                       previous_team = 2;
                }
-               else
+               else if (IsTeamSmallerThanTeam(2, previous_team, player, use_score))
                {
-                       // find first team available
-
-                       if(IS_BOT_CLIENT(for_whom))
-                       {
-                               if(c1 >= 0) { c2 = c3 = c4 = -1; }
-                               else if(c2 >= 0) { c1 = c3 = c4 = -1; }
-                               else { c1 = c2 = c4 = -1; }
-                               // no further cases, we know at least 2 teams exist
-                       }
-                       else
-                       {
-                               if(c4 >= 0) { c3 = c2 = c1 = -1; }
-                               else if(c3 >= 0) { c4 = c2 = c1 = -1; }
-                               else { c4 = c3 = c1 = -1; }
-                               // no further cases, bots have one of the teams
-                       }
+                       team_bits = BIT(1);
+                       previous_team = 2;
                }
-       }
-
-       if(!for_whom)
-               return;
-
-       // if player has a forced team, ONLY allow that one
-       if(for_whom.team_forced == NUM_TEAM_1 && c1 >= 0)
-               c2 = c3 = c4 = -1;
-       else if(for_whom.team_forced == NUM_TEAM_2 && c2 >= 0)
-               c1 = c3 = c4 = -1;
-       else if(for_whom.team_forced == NUM_TEAM_3 && c3 >= 0)
-               c1 = c2 = c4 = -1;
-       else if(for_whom.team_forced == NUM_TEAM_4 && c4 >= 0)
-               c1 = c2 = c3 = -1;
-}
-
-float PlayerValue(entity p)
-{
-       return 1;
-       // FIXME: it always returns 1...
-}
-
-// c1...c4 should be set to -1 (not allowed) or 0 (allowed).
-// teams that are allowed will now have their player counts stored in c1...c4
-void GetTeamCounts(entity ignore)
-{
-       if (MUTATOR_CALLHOOK(GetTeamCounts) == true)
-       {
-               if (c1 >= 0)
+               else if (IsTeamEqualToTeam(2, previous_team, player, use_score))
                {
-                       MUTATOR_CALLHOOK(GetTeamCount, NUM_TEAM_1, ignore, c1, numbotsteam1,
-                               lowestplayerteam1, lowestbotteam1);
-                       c1 = M_ARGV(2, float);
-                       numbotsteam1 = M_ARGV(3, float);
-                       lowestplayerteam1 = M_ARGV(4, entity);
-                       lowestbotteam1 = M_ARGV(5, entity);
+                       team_bits |= BIT(1);
+                       previous_team = 2;
                }
-               if (c2 >= 0)
+       }
+       if (Team_IsAllowed(g_team_entities[2]))
+       {
+               if (previous_team == 0)
                {
-                       MUTATOR_CALLHOOK(GetTeamCount, NUM_TEAM_2, ignore, c2, numbotsteam2,
-                               lowestplayerteam2, lowestbotteam2);
-                       c2 = M_ARGV(2, float);
-                       numbotsteam2 = M_ARGV(3, float);
-                       lowestplayerteam2 = M_ARGV(4, entity);
-                       lowestbotteam2 = M_ARGV(5, entity);
+                       team_bits = BIT(2);
+                       previous_team = 3;
                }
-               if (c3 >= 0)
+               else if (IsTeamSmallerThanTeam(3, previous_team, player, use_score))
                {
-                       MUTATOR_CALLHOOK(GetTeamCount, NUM_TEAM_3, ignore, c3, numbotsteam3,
-                               lowestplayerteam3, lowestbotteam3);
-                       c3 = M_ARGV(2, float);
-                       numbotsteam3 = M_ARGV(3, float);
-                       lowestplayerteam3 = M_ARGV(4, entity);
-                       lowestbotteam3 = M_ARGV(5, entity);
+                       team_bits = BIT(2);
+                       previous_team = 3;
                }
-               if (c4 >= 0)
+               else if (IsTeamEqualToTeam(3, previous_team, player, use_score))
                {
-                       MUTATOR_CALLHOOK(GetTeamCount, NUM_TEAM_4, ignore, c4, numbotsteam4,
-                               lowestplayerteam4, lowestbotteam4);
-                       c4 = M_ARGV(2, float);
-                       numbotsteam4 = M_ARGV(3, float);
-                       lowestplayerteam4 = M_ARGV(4, entity);
-                       lowestbotteam4 = M_ARGV(5, entity);
+                       team_bits |= BIT(2);
+                       previous_team = 3;
                }
        }
-       else
-       {
-               float value, bvalue;
-               // now count how many players are on each team already
-               float lowestplayerscore1 = FLOAT_MAX;
-               float lowestbotscore1 = FLOAT_MAX;
-               float lowestplayerscore2 = FLOAT_MAX;
-               float lowestbotscore2 = FLOAT_MAX;
-               float lowestplayerscore3 = FLOAT_MAX;
-               float lowestbotscore3 = FLOAT_MAX;
-               float lowestplayerscore4 = FLOAT_MAX;
-               float lowestbotscore4 = FLOAT_MAX;
-               FOREACH_CLIENT(true, LAMBDA(
-                       float t;
-                       if (IS_PLAYER(it) || it.caplayer)
-                       {
-                               t = it.team;
-                       }
-                       else if (it.team_forced > 0)
-                       {
-                               t = it.team_forced; // reserve the spot
-                       }
-                       else
-                       {
-                               continue;
-                       }
-                       if (it == ignore)
-                       {
-                               continue;
-                       }
-                       value = PlayerValue(it);
-                       if (IS_BOT_CLIENT(it))
-                       {
-                               bvalue = value;
-                       }
-                       else
-                       {
-                               bvalue = 0;
-                       }
-                       if (value == 0)
-                       {
-                               continue;
-                       }
-                       switch (t)
-                       {
-                               case NUM_TEAM_1:
-                               {
-                                       if (c1 < 0)
-                                       {
-                                               break;
-                                       }
-                                       c1 += value;
-                                       numbotsteam1 += bvalue;
-                                       float tempscore = PlayerScore_Get(it, SP_SCORE);
-                                       if (!bvalue)
-                                       {
-                                               if (tempscore < lowestplayerscore1)
-                                               {
-                                                       lowestplayerteam1 = it;
-                                                       lowestplayerscore1 = tempscore;
-                                               }
-                                               break;
-                                       }
-                                       if (tempscore < lowestbotscore1)
-                                       {
-                                               lowestbotteam1 = it;
-                                               lowestbotscore1 = tempscore;
-                                       }
-                                       break;
-                               }
-                               case NUM_TEAM_2:
-                               {
-                                       if (c2 < 0)
-                                       {
-                                               break;
-                                       }
-                                       c2 += value;
-                                       numbotsteam2 += bvalue;
-                                       float tempscore = PlayerScore_Get(it, SP_SCORE);
-                                       if (!bvalue)
-                                       {
-                                               if (tempscore < lowestplayerscore2)
-                                               {
-                                                       lowestplayerteam2 = it;
-                                                       lowestplayerscore2 = tempscore;
-                                               }
-                                               break;
-                                       }
-                                       if (tempscore < lowestbotscore2)
-                                       {
-                                               lowestbotteam2 = it;
-                                               lowestbotscore2 = tempscore;
-                                       }
-                                       break;
-                               }
-                               case NUM_TEAM_3:
-                               {
-                                       if (c3 < 0)
-                                       {
-                                               break;
-                                       }
-                                       c3 += value;
-                                       numbotsteam3 += bvalue;
-                                       float tempscore = PlayerScore_Get(it, SP_SCORE);
-                                       if (!bvalue)
-                                       {
-                                               if (tempscore < lowestplayerscore3)
-                                               {
-                                                       lowestplayerteam3 = it;
-                                                       lowestplayerscore3 = tempscore;
-                                               }
-                                               break;
-                                       }
-                                       if (tempscore < lowestbotscore3)
-                                       {
-                                               lowestbotteam3 = it;
-                                               lowestbotscore3 = tempscore;
-                                       }
-                                       break;
-                               }
-                               case NUM_TEAM_4:
-                               {
-                                       if (c4 < 0)
-                                       {
-                                               break;
-                                       }
-                                       c4 += value;
-                                       numbotsteam4 += bvalue;
-                                       float tempscore = PlayerScore_Get(it, SP_SCORE);
-                                       if (!bvalue)
-                                       {
-                                               if (tempscore < lowestplayerscore4)
-                                               {
-                                                       lowestplayerteam4 = it;
-                                                       lowestplayerscore4 = tempscore;
-                                               }
-                                               break;
-                                       }
-                                       if (tempscore < lowestbotscore4)
-                                       {
-                                               lowestbotteam4 = it;
-                                               lowestbotscore4 = tempscore;
-                                       }
-                                       break;
-                               }
-                       }
-               ));
-       }
-
-       // if the player who has a forced team has not joined yet, reserve the spot
-       if(autocvar_g_campaign)
+       if (Team_IsAllowed(g_team_entities[3]))
        {
-               switch(autocvar_g_campaign_forceteam)
+               if (previous_team == 0)
                {
-                       case 1: if(c1 == numbotsteam1) ++c1; break;
-                       case 2: if(c2 == numbotsteam2) ++c2; break;
-                       case 3: if(c3 == numbotsteam3) ++c3; break;
-                       case 4: if(c4 == numbotsteam4) ++c4; break;
+                       team_bits = BIT(3);
+               }
+               else if (IsTeamSmallerThanTeam(4, previous_team, player, use_score))
+               {
+                       team_bits = BIT(3);
+               }
+               else if (IsTeamEqualToTeam(4, previous_team, player, use_score))
+               {
+                       team_bits |= BIT(3);
                }
        }
+       return team_bits;
 }
 
-bool IsTeamSmallerThanTeam(int teama, int teamb, entity e, bool usescore)
+int FindBestTeamForBalance(entity player, float ignore_player)
 {
-       // equal
-       if (teama == teamb)
+       // count how many players are in each team
+       if (ignore_player)
        {
-               return false;
+               GetTeamCounts(player);
        }
-       // we assume that CheckAllowedTeams and GetTeamCounts have already been called
-       float numplayersteama = -1, numplayersteamb = -1;
-       float numbotsteama = 0, numbotsteamb = 0;
-       float scoreteama = 0, scoreteamb = 0;
-
-       switch (teama)
+       else
        {
-               case 1: numplayersteama = c1; numbotsteama = numbotsteam1; scoreteama = team1_score; break;
-               case 2: numplayersteama = c2; numbotsteama = numbotsteam2; scoreteama = team2_score; break;
-               case 3: numplayersteama = c3; numbotsteama = numbotsteam3; scoreteama = team3_score; break;
-               case 4: numplayersteama = c4; numbotsteama = numbotsteam4; scoreteama = team4_score; break;
+               GetTeamCounts(NULL);
        }
-       switch (teamb)
+       int team_bits = FindBestTeamsForBalance(player, true);
+       if (team_bits == 0)
        {
-               case 1: numplayersteamb = c1; numbotsteamb = numbotsteam1; scoreteamb = team1_score; break;
-               case 2: numplayersteamb = c2; numbotsteamb = numbotsteam2; scoreteamb = team2_score; break;
-               case 3: numplayersteamb = c3; numbotsteamb = numbotsteam3; scoreteamb = team3_score; break;
-               case 4: numplayersteamb = c4; numbotsteamb = numbotsteam4; scoreteamb = team4_score; break;
+               LOG_FATALF("FindBestTeam: No teams available for %s\n",
+                       MapInfo_Type_ToString(MapInfo_CurrentGametype()));
        }
-
-       // invalid
-       if (numplayersteama < 0 || numplayersteamb < 0)
-               return false;
-
-       if ((IS_REAL_CLIENT(e) && bots_would_leave))
+       RandomSelection_Init();
+       if ((team_bits & BIT(0)) != 0)
        {
-               numplayersteama -= numbotsteama;
-               numplayersteamb -= numbotsteamb;
+               RandomSelection_AddFloat(1, 1, 1);
        }
-       if (!usescore)
+       if ((team_bits & BIT(1)) != 0)
        {
-               return numplayersteama < numplayersteamb;
+               RandomSelection_AddFloat(2, 1, 1);
        }
-       if (numplayersteama < numplayersteamb)
+       if ((team_bits & BIT(2)) != 0)
        {
-               return true;
+               RandomSelection_AddFloat(3, 1, 1);
        }
-       if (numplayersteama > numplayersteamb)
+       if ((team_bits & BIT(3)) != 0)
        {
-               return false;
+               RandomSelection_AddFloat(4, 1, 1);
        }
-       return scoreteama < scoreteamb; 
+       return RandomSelection_chosen_float;
 }
 
-bool IsTeamEqualToTeam(int teama, int teamb, entity e, bool usescore)
+void JoinBestTeamForBalance(entity this, bool force_best_team)
 {
-       // equal
-       if (teama == teamb)
-       {
-               return true;
-       }
-       // we assume that CheckAllowedTeams and GetTeamCounts have already been called
-       float numplayersteama = -1, numplayersteamb = -1;
-       float numbotsteama = 0, numbotsteamb = 0;
-       float scoreteama = 0, scoreteamb = 0;
-
-       switch (teama)
-       {
-               case 1: numplayersteama = c1; numbotsteama = numbotsteam1; scoreteama = team1_score; break;
-               case 2: numplayersteama = c2; numbotsteama = numbotsteam2; scoreteama = team2_score; break;
-               case 3: numplayersteama = c3; numbotsteama = numbotsteam3; scoreteama = team3_score; break;
-               case 4: numplayersteama = c4; numbotsteama = numbotsteam4; scoreteama = team4_score; break;
-       }
-       switch (teamb)
+       // don't join a team if we're not playing a team game
+       if (!teamplay)
        {
-               case 1: numplayersteamb = c1; numbotsteamb = numbotsteam1; scoreteamb = team1_score; break;
-               case 2: numplayersteamb = c2; numbotsteamb = numbotsteam2; scoreteamb = team2_score; break;
-               case 3: numplayersteamb = c3; numbotsteamb = numbotsteam3; scoreteamb = team3_score; break;
-               case 4: numplayersteamb = c4; numbotsteamb = numbotsteam4; scoreteamb = team4_score; break;
+               return;
        }
 
-       // invalid
-       if (numplayersteama < 0 || numplayersteamb < 0)
-               return false;
-
-       if ((IS_REAL_CLIENT(e) && bots_would_leave))
-       {
-               numplayersteama -= numbotsteama;
-               numplayersteamb -= numbotsteamb;
-       }
-       if (!usescore)
-       {
-               return numplayersteama == numplayersteamb;
-       }
-       if (numplayersteama < numplayersteamb)
-       {
-               return false;
-       }
-       if (numplayersteama > numplayersteamb)
-       {
-               return false;
-       }
-       return scoreteama == scoreteamb;        
-}
+       // find out what teams are available
+       CheckAllowedTeams(this);
 
-int FindBestTeams(entity player, bool usescore)
-{
-       if (MUTATOR_CALLHOOK(FindBestTeams, player) == true)
+       // if we don't care what team they end up on, put them on whatever team they entered as.
+       // if they're not on a valid team, then let other code put them on the smallest team
+       if (!force_best_team)
        {
-               return M_ARGV(1, float);
-       }
-       int teambits = 0;
-       int previousteam = 0;
-       if (c1 >= 0)
-       {
-               teambits = BIT(0);
-               previousteam = 1;
-       }
-       if (c2 >= 0)
-       {
-               if (IsTeamSmallerThanTeam(2, previousteam, player, usescore))
+               int selected_team_num = -1;
+               for (int i = 0; i < 4; ++i)
                {
-                       teambits = BIT(1);
-                       previousteam = 2;
+                       if (Team_IsAllowed(g_team_entities[i]) && (this.team ==
+                               Team_NumberToTeam(i)))
+                       {
+                               selected_team_num = this.team;
+                               break;
+                       }
                }
-               else if (IsTeamEqualToTeam(2, previousteam, player, usescore))
+               
+               if (Team_IsValidTeam(selected_team_num))
                {
-                       teambits |= BIT(1);
-                       previousteam = 2;
+                       SetPlayerTeamSimple(this, selected_team_num);
+                       LogTeamchange(this.playerid, this.team, 99);
+                       return;
                }
        }
-       if (c3 >= 0)
+       // otherwise end up on the smallest team (handled below)
+       if (this.bot_forced_team)
        {
-               if (IsTeamSmallerThanTeam(3, previousteam, player, usescore))
-               {
-                       teambits = BIT(2);
-                       previousteam = 3;
-               }
-               else if (IsTeamEqualToTeam(3, previousteam, player, usescore))
-               {
-                       teambits |= BIT(2);
-                       previousteam = 3;
-               }
+               return;
        }
-       if (c4 >= 0)
+       int best_team_index = FindBestTeamForBalance(this, true);
+       int best_team_num = Team_NumberToTeam(best_team_index);
+       int old_team_index = Team_TeamToNumber(this.team);
+       TeamchangeFrags(this);
+       SetPlayerTeamSimple(this, best_team_num);
+       LogTeamchange(this.playerid, this.team, 2); // log auto join
+       if ((old_team_index != -1) && !IS_BOT_CLIENT(this))
        {
-               if (IsTeamSmallerThanTeam(4, previousteam, player, usescore))
-               {
-                       teambits = BIT(3);
-               }
-               else if (IsTeamEqualToTeam(4, previousteam, player, usescore))
-               {
-                       teambits |= BIT(3);
-               }
+               AutoBalanceBots(old_team_index, best_team_index);
        }
-       return teambits;
+       KillPlayerForTeamChange(this);
 }
 
-// returns # of smallest team (1, 2, 3, 4)
-// NOTE: Assumes CheckAllowedTeams has already been called!
-float FindSmallestTeam(entity pl, float ignore_pl)
+bool IsTeamSmallerThanTeam(int team_index_a, int team_index_b, entity player,
+       bool use_score)
 {
-       // count how many players are in each team
-       if (ignore_pl)
+       if (!Team_IsValidIndex(team_index_a))
        {
-               GetTeamCounts(pl);
+               LOG_FATALF("IsTeamSmallerThanTeam: team_index_a is invalid: %f",
+                       team_index_a);
        }
-       else
+       if (!Team_IsValidIndex(team_index_b))
        {
-               GetTeamCounts(NULL);
+               LOG_FATALF("IsTeamSmallerThanTeam: team_index_b is invalid: %f",
+                       team_index_b);
        }
-       int teambits = FindBestTeams(pl, true);
-       if (teambits == 0)
+       if (team_index_a == team_index_b)
        {
-               error(sprintf("No teams available for %s\n", MapInfo_Type_ToString(MapInfo_CurrentGametype())));
+               return false;
        }
-       RandomSelection_Init();
-       if ((teambits & BIT(0)) != 0)
+       entity team_a = Team_GetTeamFromIndex(team_index_a);
+       entity team_b = Team_GetTeamFromIndex(team_index_b);
+       if (!Team_IsAllowed(team_a) || !Team_IsAllowed(team_b))
        {
-               RandomSelection_AddFloat(1, 1, 1);
+               return false;
        }
-       if ((teambits & BIT(1)) != 0)
+       int num_players_team_a = team_a.m_num_players;
+       int num_players_team_b = team_b.m_num_players;
+       if (IS_REAL_CLIENT(player) && bots_would_leave)
        {
-               RandomSelection_AddFloat(2, 1, 1);
+               num_players_team_a -= team_a.m_num_bots;
+               num_players_team_b -= team_b.m_num_bots;
        }
-       if ((teambits & BIT(2)) != 0)
+       if (!use_score)
        {
-               RandomSelection_AddFloat(3, 1, 1);
+               return num_players_team_a < num_players_team_b;
        }
-       if ((teambits & BIT(3)) != 0)
+       if (num_players_team_a < num_players_team_b)
        {
-               RandomSelection_AddFloat(4, 1, 1);
+               return true;
        }
-       return RandomSelection_chosen_float;
+       if (num_players_team_a > num_players_team_b)
+       {
+               return false;
+       }
+       return team_a.m_team_score < team_b.m_team_score;
 }
 
-int JoinBestTeam(entity this, bool only_return_best, bool forcebestteam)
+bool IsTeamEqualToTeam(int team_index_a, int team_index_b, entity player,
+       bool use_score)
 {
-       // don't join a team if we're not playing a team game
-       if (!teamplay)
+       if (!Team_IsValidIndex(team_index_a))
        {
-               return 0;
+               LOG_FATALF("IsTeamEqualToTeam: team_index_a is invalid: %f",
+                       team_index_a);
        }
-
-       // find out what teams are available
-       CheckAllowedTeams(this);
-
-       float selectedteam;
-
-       // if we don't care what team he ends up on, put him on whatever team he entered as.
-       // if he's not on a valid team, then let other code put him on the smallest team
-       if (!forcebestteam)
+       if (!Team_IsValidIndex(team_index_b))
        {
-               if(     c1 >= 0 && this.team == NUM_TEAM_1)
-                       selectedteam = this.team;
-               else if(c2 >= 0 && this.team == NUM_TEAM_2)
-                       selectedteam = this.team;
-               else if(c3 >= 0 && this.team == NUM_TEAM_3)
-                       selectedteam = this.team;
-               else if(c4 >= 0 && this.team == NUM_TEAM_4)
-                       selectedteam = this.team;
-               else
-                       selectedteam = -1;
-
-               if (selectedteam > 0)
-               {
-                       if (!only_return_best)
-                       {
-                               SetPlayerTeamSimple(this, selectedteam);
-
-                               // when JoinBestTeam is called by client.qc/ClientKill_Now_TeamChange the players team is -1 and thus skipped
-                               // when JoinBestTeam is called by client.qc/ClientConnect the player_id is 0 the log attempt is rejected
-                               LogTeamchange(this.playerid, this.team, 99);
-                       }
-                       return selectedteam;
-               }
-               // otherwise end up on the smallest team (handled below)
+               LOG_FATALF("IsTeamEqualToTeam: team_index_b is invalid: %f",
+                       team_index_b);
        }
-
-       float bestteam = FindSmallestTeam(this, true);
-       if (only_return_best || this.bot_forced_team)
+       if (team_index_a == team_index_b)
        {
-               return bestteam;
+               return true;
        }
-       bestteam = Team_NumberToTeam(bestteam);
-       if (bestteam == -1)
+       entity team_a = Team_GetTeamFromIndex(team_index_a);
+       entity team_b = Team_GetTeamFromIndex(team_index_b);
+       if (!Team_IsAllowed(team_a) || !Team_IsAllowed(team_b))
        {
-               error("JoinBestTeam: invalid team\n");
+               return false;
        }
-       int oldteam = Team_TeamToNumber(this.team);
-       TeamchangeFrags(this);
-       SetPlayerTeamSimple(this, bestteam);
-       LogTeamchange(this.playerid, this.team, 2); // log auto join
-       if (!IS_BOT_CLIENT(this))
+       int num_players_team_a = team_a.m_num_players;
+       int num_players_team_b = team_b.m_num_players;
+       if (IS_REAL_CLIENT(player) && bots_would_leave)
        {
-               AutoBalanceBots(oldteam, Team_TeamToNumber(bestteam));
+               num_players_team_a -= team_a.m_num_bots;
+               num_players_team_b -= team_b.m_num_bots;
        }
-       if (!IS_DEAD(this) && (MUTATOR_CALLHOOK(Player_ChangeTeamKill, this) ==
-               false))
+       if (!use_score)
        {
-               Damage(this, this, this, 100000, DEATH_TEAMCHANGE.m_id, this.origin, '0 0 0');
+               return num_players_team_a == num_players_team_b;
        }
-       return bestteam;
+       if (num_players_team_a != num_players_team_b)
+       {
+               return false;
+       }
+       return team_a.m_team_score == team_b.m_team_score;
 }
 
 void SV_ChangeTeam(entity this, float _color)
 {
-       float sourcecolor, destinationcolor, sourceteam, destinationteam;
+       int source_color, destination_color;
+       int source_team_index, destination_team_index;
 
        // in normal deathmatch we can just apply the color and we're done
        if(!teamplay)
@@ -808,28 +855,32 @@ void SV_ChangeTeam(entity this, float _color)
        if(!teamplay)
                return;
 
-       sourcecolor = this.clientcolors & 0x0F;
-       destinationcolor = _color & 0x0F;
+       source_color = this.clientcolors & 0x0F;
+       destination_color = _color & 0x0F;
+
+       source_team_index = Team_TeamToNumber(source_color + 1);
+       destination_team_index = Team_TeamToNumber(destination_color + 1);
+
+       if (destination_team_index == -1)
+       {
+               return;
+       }
 
-       sourceteam = Team_TeamToNumber(sourcecolor + 1);
-       destinationteam = Team_TeamToNumber(destinationcolor + 1);
-       
        CheckAllowedTeams(this);
 
-       if (destinationteam == 1 && c1 < 0) destinationteam = 4;
-       if (destinationteam == 4 && c4 < 0) destinationteam = 3;
-       if (destinationteam == 3 && c3 < 0) destinationteam = 2;
-       if (destinationteam == 2 && c2 < 0) destinationteam = 1;
+       if (destination_team_index == 1 && !Team_IsAllowed(g_team_entities[0])) destination_team_index = 4;
+       if (destination_team_index == 4 && !Team_IsAllowed(g_team_entities[3])) destination_team_index = 3;
+       if (destination_team_index == 3 && !Team_IsAllowed(g_team_entities[2])) destination_team_index = 2;
+       if (destination_team_index == 2 && !Team_IsAllowed(g_team_entities[1])) destination_team_index = 1;
 
        // not changing teams
-       if (sourcecolor == destinationcolor)
+       if (source_color == destination_color)
        {
-               SetPlayerTeam(this, destinationteam, sourceteam, true);
+               SetPlayerTeam(this, destination_team_index, source_team_index, true);
                return;
        }
 
-       if (autocvar_g_campaign || (autocvar_g_changeteam_banned && this.wasplayer))
-       {
+       if((autocvar_g_campaign) || (autocvar_g_changeteam_banned && CS(this).wasplayer)) {
                Send_Notification(NOTIF_ONE, this, MSG_INFO, INFO_TEAMCHANGE_NOTALLOWED);
                return; // changing teams is not allowed
        }
@@ -838,237 +889,61 @@ void SV_ChangeTeam(entity this, float _color)
        if (autocvar_g_balance_teams && autocvar_g_balance_teams_prevent_imbalance)
        {
                GetTeamCounts(this);
-               if ((BIT(destinationteam - 1) & FindBestTeams(this, false)) == 0)
+               if ((BIT(destination_team_index - 1) & FindBestTeamsForBalance(this, false)) == 0)
                {
                        Send_Notification(NOTIF_ONE, this, MSG_INFO, INFO_TEAMCHANGE_LARGERTEAM);
                        return;
                }
        }
-       if(IS_PLAYER(this) && sourceteam != destinationteam)
+       if (IS_PLAYER(this) && source_team_index != destination_team_index)
        {
                // reduce frags during a team change
                TeamchangeFrags(this);
        }
-       SetPlayerTeam(this, destinationteam, sourceteam, !IS_CLIENT(this));
-       AutoBalanceBots(sourceteam, destinationteam);
-       if (!IS_PLAYER(this) || (sourceteam == destinationteam))
-       {
-               return;
-       }
-       // kill player when changing teams
-       if (IS_DEAD(this) || (MUTATOR_CALLHOOK(Player_ChangeTeamKill, this) == true))
-       {
-               return;
-       }
-       Damage(this, this, this, 100000, DEATH_TEAMCHANGE.m_id, this.origin, '0 0 0');
-}
-
-void AutoBalanceBots(int sourceteam, int destinationteam)
-{
-       if ((sourceteam == -1) || (destinationteam == -1))
+       if (!SetPlayerTeam(this, destination_team_index, source_team_index,
+               !IS_CLIENT(this)))
        {
                return;
        }
-       if (!autocvar_g_balance_teams ||
-               !autocvar_g_balance_teams_prevent_imbalance)
+       AutoBalanceBots(source_team_index, destination_team_index);
+       if (!IS_PLAYER(this) || (source_team_index == destination_team_index))
        {
                return;
        }
-       int numplayerssourceteam = 0;
-       int numplayersdestinationteam = 0;
-       entity lowestbotdestinationteam = NULL;
-       switch (sourceteam)
-       {
-               case 1:
-               {
-                       numplayerssourceteam = c1;
-                       break;
-               }
-               case 2:
-               {
-                       numplayerssourceteam = c2;
-                       break;
-               }
-               case 3:
-               {
-                       numplayerssourceteam = c3;
-                       break;
-               }
-               case 4:
-               {
-                       numplayerssourceteam = c4;
-                       break;
-               }
-       }
-       switch (destinationteam)
-       {
-               case 1:
-               {
-                       numplayersdestinationteam = c1;
-                       lowestbotdestinationteam = lowestbotteam1;
-                       break;
-               }
-               case 2:
-               {
-                       numplayersdestinationteam = c2;
-                       lowestbotdestinationteam = lowestbotteam2;
-                       break;
-               }
-               case 3:
-               {
-                       numplayersdestinationteam = c3;
-                       lowestbotdestinationteam = lowestbotteam3;
-                       break;
-               }
-               case 4:
-               {
-                       numplayersdestinationteam = c4;
-                       lowestbotdestinationteam = lowestbotteam4;
-                       break;
-               }
-       }
-       if ((numplayersdestinationteam > numplayerssourceteam) && (lowestbotdestinationteam != NULL))
-       {
-               SetPlayerTeamSimple(lowestbotdestinationteam, Team_NumberToTeam(sourceteam));
-       }
+       KillPlayerForTeamChange(this);
 }
 
-void ShufflePlayerOutOfTeam (float source_team)
+void AutoBalanceBots(int source_team_index, int destination_team_index)
 {
-       float smallestteam, smallestteam_count, steam;
-       float lowest_bot_score, lowest_player_score;
-       entity lowest_bot, lowest_player, selected;
-
-       smallestteam = 0;
-       smallestteam_count = 999999999;
-
-       if(c1 >= 0 && c1 < smallestteam_count)
+       if (!Team_IsValidIndex(source_team_index))
        {
-               smallestteam = 1;
-               smallestteam_count = c1;
-       }
-       if(c2 >= 0 && c2 < smallestteam_count)
-       {
-               smallestteam = 2;
-               smallestteam_count = c2;
-       }
-       if(c3 >= 0 && c3 < smallestteam_count)
-       {
-               smallestteam = 3;
-               smallestteam_count = c3;
-       }
-       if(c4 >= 0 && c4 < smallestteam_count)
-       {
-               smallestteam = 4;
-               smallestteam_count = c4;
-       }
-
-       if(!smallestteam)
-       {
-               bprint("warning: no smallest team\n");
+               LOG_WARNF("AutoBalanceBots: Source team index is invalid: %f",
+                       source_team_index);
                return;
        }
-
-       if(source_team == 1)
-               steam = NUM_TEAM_1;
-       else if(source_team == 2)
-               steam = NUM_TEAM_2;
-       else if(source_team == 3)
-               steam = NUM_TEAM_3;
-       else // if(source_team == 4)
-               steam = NUM_TEAM_4;
-
-       lowest_bot = NULL;
-       lowest_bot_score = 999999999;
-       lowest_player = NULL;
-       lowest_player_score = 999999999;
-
-       // find the lowest-scoring player & bot of that team
-       FOREACH_CLIENT(IS_PLAYER(it) && it.team == steam, LAMBDA(
-               if(it.isbot)
-               {
-                       if(it.totalfrags < lowest_bot_score)
-                       {
-                               lowest_bot = it;
-                               lowest_bot_score = it.totalfrags;
-                       }
-               }
-               else
-               {
-                       if(it.totalfrags < lowest_player_score)
-                       {
-                               lowest_player = it;
-                               lowest_player_score = it.totalfrags;
-                       }
-               }
-       ));
-
-       // prefers to move a bot...
-       if(lowest_bot != NULL)
-               selected = lowest_bot;
-       // but it will move a player if it has to
-       else
-               selected = lowest_player;
-       // don't do anything if it couldn't find anyone
-       if(!selected)
+       if (!Team_IsValidIndex(destination_team_index))
        {
-               bprint("warning: couldn't find a player to move from team\n");
+               LOG_WARNF("AutoBalanceBots: Destination team index is invalid: %f",
+                       destination_team_index);
                return;
        }
-
-       // smallest team gains a member
-       if(smallestteam == 1)
-       {
-               c1 = c1 + 1;
-       }
-       else if(smallestteam == 2)
-       {
-               c2 = c2 + 1;
-       }
-       else if(smallestteam == 3)
-       {
-               c3 = c3 + 1;
-       }
-       else if(smallestteam == 4)
-       {
-               c4 = c4 + 1;
-       }
-       else
+       if (!autocvar_g_balance_teams ||
+               !autocvar_g_balance_teams_prevent_imbalance)
        {
-               bprint("warning: destination team invalid\n");
                return;
        }
-       // source team loses a member
-       if(source_team == 1)
-       {
-               c1 = c1 + 1;
-       }
-       else if(source_team == 2)
-       {
-               c2 = c2 + 2;
-       }
-       else if(source_team == 3)
+       entity source_team = Team_GetTeamFromIndex(source_team_index);
+       if (!Team_IsAllowed(source_team))
        {
-               c3 = c3 + 3;
-       }
-       else if(source_team == 4)
-       {
-               c4 = c4 + 4;
-       }
-       else
-       {
-               bprint("warning: source team invalid\n");
                return;
        }
-
-       // move the player to the new team
-       TeamchangeFrags(selected);
-       SetPlayerTeam(selected, smallestteam, source_team, false);
-
-       if (IS_DEAD(selected) || MUTATOR_CALLHOOK(Player_ChangeTeamKill, selected) == true)
+       entity destination_team = Team_GetTeamFromIndex(destination_team_index);
+       if ((destination_team.m_num_players <= source_team.m_num_players) ||
+               (destination_team.m_lowest_bot == NULL))
        {
                return;
        }
-       Damage(selected, selected, selected, 100000, DEATH_AUTOTEAMCHANGE.m_id, selected.origin, '0 0 0');
-       Send_Notification(NOTIF_ONE, selected, MSG_CENTER, CENTER_DEATH_SELF_AUTOTEAMCHANGE, selected.team);
+       SetPlayerTeamSimple(destination_team.m_lowest_bot,
+               Team_NumberToTeam(source_team_index));
+       KillPlayerForTeamChange(destination_team.m_lowest_bot);
 }