$execute store result score #red_players game$(map_id) run execute if entity @a[team=red]
$execute store result score #blue_players game$(map_id) run execute if entity @a[team=blue]

execute store result score .red temp run execute if entity @a[team=red]
execute store result score .blue temp run execute if entity @a[team=blue]
execute store result score .red_difference temp run scoreboard players operation .red temp -= .blue temp

execute store result score .red temp run execute if entity @a[team=red]
execute store result score .blue temp run execute if entity @a[team=blue]
execute store result score .blue_difference temp run scoreboard players operation .blue temp -= .red temp

$execute if score #red_players game$(map_id) matches 0 if score #blue_players game$(map_id) matches 0 run return run scoreboard players set .player_state temp -1

# teams are equal, do nothing
$execute if score #red_players game$(map_id) = #blue_players game$(map_id) run return run scoreboard players set .player_state temp 0

# teams are not equal, make sure there is at least 1 player on each team
$execute if score #red_players game$(map_id) matches 1.. if score #blue_players game$(map_id) matches 1.. run scoreboard players set .player_state temp 1

# if they do not, set state to -1
$execute unless score #red_players game$(map_id) matches 1.. run scoreboard players set .player_state temp -1
$execute unless score #blue_players game$(map_id) matches 1.. run scoreboard players set .player_state temp -1

execute if score .player_state temp matches -1 run return 0

# see if red has more
$execute if score #red_players game$(map_id) > #blue_players game$(map_id) run scoreboard players set .player_state temp 2

# see if blue has more
$execute if score #blue_players game$(map_id) > #red_players game$(map_id) run scoreboard players set .player_state temp 3

execute unless score .blue_difference temp matches -1 if score .player_state temp matches 2 run tellraw @a[tag=dev] {"text":"Red has more players! Auto Balancing teams...","color":"gold"}
execute unless score .red_difference temp matches -1 if score .player_state temp matches 3 run tellraw @a[tag=dev] {"text":"Blue has more players! Auto Balancing teams...","color":"gold"}

execute if score .auto_balance settings matches 0 run return run scoreboard players set .player_state temp 0

execute unless score .blue_difference temp matches -1 if score .player_state temp matches 2 run function pctf:logic/lobby/balance_players/red_has_more with storage pctf:map input

execute unless score .red_difference temp matches -1 if score .player_state temp matches 3 run function pctf:logic/lobby/balance_players/blue_has_more with storage pctf:map input