Hadlock

insanebalancer0.0.0.5withpatch.cs

Dec 10th, 2011
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 215.14 KB | None | 0 0
  1. /*
  2.  * Copyright 2011 Miguel Mendoza - miguel@micovery.com
  3.  *
  4.  * Insane Balancer is free software: you can redistribute it and/or modify it under the terms of the
  5.  * GNU General Public License as published by the Free Software Foundation, either version 3 of the License,
  6.  * or (at your option) any later version. Insane Balancer is distributed in the hope that it will be useful,
  7.  * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  8.  * See the GNU General Public License for more details. You should have received a copy of the
  9.  * GNU General Public License along with Insane Balancer. If not, see http://www.gnu.org/licenses/.
  10.  *
  11.  */
  12.  
  13. using System;
  14. using System.IO;
  15. using System.Text;
  16. using System.Reflection;
  17. using System.Collections.Generic;
  18. using System.Collections;
  19. using System.Net;
  20. using System.Threading;
  21.  
  22.  
  23. using System.Web;
  24. using System.Data;
  25. using System.Text.RegularExpressions;
  26.  
  27. using PRoCon.Core;
  28. using PRoCon.Core.Plugin;
  29. using PRoCon.Core.Plugin.Commands;
  30. using PRoCon.Core.Players;
  31. using PRoCon.Core.Players.Items;
  32. using PRoCon.Core.Battlemap;
  33. using PRoCon.Core.Maps;
  34.  
  35. namespace PRoConEvents
  36. {
  37.  
  38.     public class InsaneBalancer : PRoConPluginAPI, IPRoConPluginInterface
  39.     {
  40.  
  41.         int check_state_phase = 0;
  42.         int login_state = 0;
  43.         bool delayed_connect = false;
  44.         int win_teamId, lose_teamId;
  45.         public bool round_balancer = false;
  46.         public bool live_balancer = false;
  47.         public bool level_started = false;
  48.         bool sleep = false;
  49.         bool virtual_mode = false;
  50.         int max_player_count = 0;
  51.         public BattleLog blog = null;
  52.         public int attempts = 0;
  53.  
  54.  
  55.  
  56.  
  57.         public class BattleLog
  58.         {
  59.  
  60.             private String login = "https://battlelog.battlefield.com/bf3/gate/login/";
  61.             private String gate = "https://battlelog.battlefield.com/bf3/gate";
  62.             private String redirect = "http://battlelog.battlefield.com/bf3/";
  63.             private HttpWebRequest req = null;
  64.             private CookieContainer cookies = null;
  65.             private InsaneBalancer plugin = null;
  66.  
  67.             bool connected = false;
  68.             bool authenticated = false;
  69.             public bool isConnected()
  70.             {
  71.                 return connected;
  72.             }
  73.  
  74.             public bool isAuthenticated()
  75.             {
  76.                 return authenticated;
  77.             }
  78.  
  79.             public bool isReady()
  80.             {
  81.                 return isConnected() && isAuthenticated();
  82.             }
  83.  
  84.             public BattleLog(InsaneBalancer plugin)
  85.             {
  86.                 this.plugin = plugin;
  87.             }
  88.  
  89.             public bool connect()
  90.             {
  91.                 try
  92.                 {
  93.                     /* allow only one connection per instance */
  94.                     if (isConnected())
  95.                         return true;
  96.  
  97.                     plugin.ConsoleWrite("Connecting to ^b" + gate);
  98.  
  99.                     /* make the cookie jar (-: */
  100.                     cookies = new CookieContainer();
  101.  
  102.  
  103.  
  104.                     /*make the http request */
  105.                     req = (HttpWebRequest)WebRequest.Create(gate);
  106.  
  107.  
  108.                     req.CookieContainer = cookies;
  109.                     req.Method = "GET";
  110.                     req.KeepAlive = true;
  111.                     req.Timeout = 10000;
  112.  
  113.  
  114.                     req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
  115.                     req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.106 Safari/535.2";
  116.                     req.Referer = gate;
  117.                     req.Headers = new WebHeaderCollection();
  118.                     req.Headers.Add("Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3");
  119.                     req.Headers.Add("Accept-Encoding:gzip,deflate,sdch");
  120.                     req.Headers.Add("Accept-Language:en-US,en;q=0.8");
  121.                     req.Headers.Add("Cache-Control:max-age=0");
  122.  
  123.  
  124.  
  125.                     //plugin.ConsoleWrite("sending!");
  126.                     HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
  127.  
  128.                     if (resp.StatusCode == HttpStatusCode.OK)
  129.                     {
  130.                         plugin.ConsoleWrite("connection succeeded!");
  131.                         connected = true;
  132.                         return true;
  133.                     }
  134.  
  135.                     plugin.ConsoleWrite("connection failed, HTTP: " + resp.StatusCode + " " + resp.StatusDescription);
  136.  
  137.                     connected = false;
  138.                 }
  139.                 catch (Exception e)
  140.                 {
  141.                     plugin.dump_exception(e);
  142.                 }
  143.                 return false;
  144.             }
  145.  
  146.             public bool authenticate(String user, String pass)
  147.             {
  148.                 try
  149.                 {
  150.                     /* cannot authenticate if not connected */
  151.                     if (!isConnected())
  152.                         return false;
  153.  
  154.                     /* allow only one authentication per instance */
  155.                     if (isAuthenticated())
  156.                         return true;
  157.  
  158.                     /*make the http request */
  159.  
  160.  
  161.                     req = (HttpWebRequest)WebRequest.Create(login);
  162.  
  163.                     /* set the cookie from the previous connection */
  164.                     req.CookieContainer = cookies;
  165.                     req.Method = "POST";
  166.                     req.Timeout = 10000;
  167.  
  168.  
  169.                     /* make the headers */
  170.                     req.Referer = gate;
  171.                     req.Headers = new WebHeaderCollection();
  172.                     req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
  173.                     req.KeepAlive = true;
  174.                     req.ContentType = "application/x-www-form-urlencoded";
  175.                     req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.106 Safari/535.2";
  176.                     req.Headers.Add("Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3");
  177.                     req.Headers.Add("Accept-Encoding:gzip,deflate,sdch");
  178.                     req.Headers.Add("Accept-Language:en-US,en;q=0.8");
  179.                     req.Headers.Add("Cache-Control:max-age=0");
  180.  
  181.                     /* encode the post data */
  182.                     String data = "email=" + System.Uri.EscapeDataString(user) + "&password=" + System.Uri.EscapeDataString(pass) + "&submit=" + System.Uri.EscapeDataString("Sign in") + "&redirect=";
  183.  
  184.                     byte[] bytes = System.Text.Encoding.ASCII.GetBytes(data);
  185.                     req.ContentLength = bytes.Length;
  186.  
  187.                     /* add the body of the request */
  188.                     Stream strm = req.GetRequestStream();
  189.                     strm.Write(bytes, 0, bytes.Length);
  190.                     strm.Close();
  191.  
  192.                     /* dont want to follow HTTP 301 */
  193.                     req.AllowAutoRedirect = false;
  194.  
  195.  
  196.                     plugin.DebugWrite("Request Headers: ", 5);
  197.                     for (int i = 0; i < req.Headers.Count; ++i)
  198.                         plugin.DebugWrite("    " + req.Headers.Keys[i] + ":" + req.Headers[i], 5);
  199.  
  200.                     HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
  201.  
  202.                     plugin.DebugWrite("Response Headers: ", 5);
  203.                     String location = "";
  204.                     for (int i = 0; i < resp.Headers.Count; ++i)
  205.                     {
  206.                         plugin.DebugWrite("    " + resp.Headers.Keys[i] + ":" + resp.Headers[i], 5);
  207.                         if (resp.Headers.Keys[i].Equals("Location"))
  208.                             location = resp.Headers[i];
  209.                     }
  210.  
  211.                     //plugin.ConsoleWrite("Location: " + location);
  212.                     if (resp.StatusCode == HttpStatusCode.Redirect && location.Equals(redirect))
  213.                     {
  214.                         plugin.ConsoleWrite("authentication succeeded!");
  215.                         authenticated = true;
  216.                         return true;
  217.                     }
  218.  
  219.                     plugin.ConsoleWrite("authentication failed, HTTP " + resp.StatusCode + " " + resp.StatusDescription);
  220.  
  221.                     authenticated = false;
  222.                 }
  223.                 catch (Exception e)
  224.                 {
  225.                     plugin.dump_exception(e);
  226.                 }
  227.                 return false;
  228.             }
  229.  
  230.             public String getPlayerTag(String name)
  231.             {
  232.  
  233.                 try
  234.                 {
  235.                     if (!isReady())
  236.                         return "";
  237.  
  238.                     plugin.ConsoleWrite("Getting battlelog stats for ^b" + name);
  239.  
  240.                     String address = "http://battlelog.battlefield.com/bf3/user/" + name;
  241.  
  242.                     /*make the http request */
  243.                     req = (HttpWebRequest)WebRequest.Create(address);
  244.  
  245.  
  246.                     req.CookieContainer = cookies;
  247.                     req.Method = "GET";
  248.                     req.KeepAlive = true;
  249.                     req.Timeout = 10000;
  250.  
  251.                     req.Accept = "Accept: */*";
  252.                     req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.106 Safari/535.2";
  253.                     req.Referer = address;
  254.  
  255.                     req.Headers = new WebHeaderCollection();
  256.                     req.Headers.Add("Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3");
  257.                     //req.Headers.Add("Accept-Encoding:gzip,deflate,sdch");
  258.  
  259.                     req.Headers.Add("Accept-Language:en-US,en;q=0.8");
  260.                     req.Headers.Add("X-AjaxNavigation:1");
  261.  
  262.                     req.Headers.Add("X-Requested-With:XMLHttpRequest");
  263.                     req.Headers.Add("Cache-Control:max-age=0");
  264.  
  265.                     HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
  266.  
  267.                     if (resp.StatusCode == HttpStatusCode.OK)
  268.                     {
  269.                         String result = "";
  270.  
  271.                         Encoding responseEncoding = Encoding.GetEncoding(resp.CharacterSet);
  272.                         StreamReader sr = new StreamReader(resp.GetResponseStream(), responseEncoding);
  273.                         result = sr.ReadToEnd();
  274.                         Match clanTagMatch = Regex.Match(result, @"clanTag"":""([^""]+)""", RegexOptions.IgnoreCase);
  275.  
  276.                         String tag = "";
  277.                         if (clanTagMatch.Success)
  278.                             return clanTagMatch.Groups[1].Value;
  279.  
  280.                         return tag;
  281.                     }
  282.  
  283.                     plugin.ConsoleWrite("connection failed, HTTP: " + resp.StatusCode + " " + resp.StatusDescription);
  284.  
  285.                 }
  286.                 catch (Exception e)
  287.                 {
  288.                     plugin.dump_exception(e);
  289.                 }
  290.                 return "";
  291.             }
  292.         }
  293.  
  294.  
  295.         private class PlayerSquad
  296.         {
  297.             public List<PlayerProfile> members;
  298.             int squadId = 0;
  299.             int teamId = 0;
  300.  
  301.             public PlayerSquad(int tid, int sid)
  302.             {
  303.                 members = new List<PlayerProfile>();
  304.                 teamId = tid;
  305.                 squadId = sid;
  306.             }
  307.  
  308.             public PlayerSquad(PlayerSquad squad)
  309.             {
  310.                 squadId = squad.squadId;
  311.                 teamId = squad.squadId;
  312.                 members = squad.members;
  313.             }
  314.  
  315.             private bool playerBelongs(PlayerProfile player)
  316.             {
  317.                 return getTeamId() == player.getTeamId() && getSquadId() == player.getSquadId();
  318.             }
  319.  
  320.             public bool hasPlayer(PlayerProfile player)
  321.             {
  322.                 return members.Contains(player);
  323.             }
  324.  
  325.             public int getFreeSlots()
  326.             {
  327.                 if (getSquadId() == 0)
  328.                     return 32;
  329.  
  330.                 return 4 - getCount();
  331.             }
  332.  
  333.             public bool addPlayer(PlayerProfile player)
  334.             {
  335.                 if (!playerBelongs(player) || hasPlayer(player))
  336.                     return false;
  337.  
  338.                 members.Add(player);
  339.                 return true;
  340.             }
  341.  
  342.             public virtual int getTeamId()
  343.             {
  344.                 return teamId;
  345.             }
  346.  
  347.             public virtual int getSquadId()
  348.             {
  349.                 return squadId;
  350.             }
  351.  
  352.  
  353.             public bool dropPlayer(PlayerProfile player)
  354.             {
  355.                 if (!members.Contains(player))
  356.                     return false;
  357.  
  358.                 members.Remove(player);
  359.                 return true;
  360.             }
  361.  
  362.  
  363.  
  364.             public virtual PlayerProfile getRandomPlayer()
  365.             {
  366.                 int pcount = getCount();
  367.                 if (pcount == 0)
  368.                     return null;
  369.  
  370.                 return getMembers()[(new Random()).Next(pcount)];
  371.             }
  372.  
  373.             public PlayerProfile removeRandomPlayer()
  374.             {
  375.                 PlayerProfile player = getRandomPlayer();
  376.                 if (player == null)
  377.                     return null;
  378.  
  379.                 dropPlayer(player);
  380.                 return player;
  381.             }
  382.  
  383.             public void sortMembers(player_sort_method sort_method)
  384.             {
  385.                 this.members.Sort(new Comparison<PlayerProfile>(sort_method));
  386.  
  387.             }
  388.  
  389.             public int getCount()
  390.             {
  391.                 return members.Count;
  392.             }
  393.  
  394.             public List<PlayerProfile> getMembers()
  395.             {
  396.                 return members;
  397.             }
  398.  
  399.             public double getRoundSpm()
  400.             {
  401.                 int count = getCount();
  402.                 if (count == 0)
  403.                     return 0;
  404.  
  405.                 double spm = 0;
  406.                 foreach (PlayerProfile player in getMembers())
  407.                 {
  408.                     spm += player.getRoundSpm();
  409.                 }
  410.  
  411.                 return (spm / count);
  412.             }
  413.  
  414.             public double getRoundKpm()
  415.             {
  416.                 int count = getCount();
  417.                 if (count == 0)
  418.                     return 0;
  419.  
  420.                 double kpm = 0;
  421.                 foreach (PlayerProfile player in getMembers())
  422.                 {
  423.                     kpm += player.getRoundKpm();
  424.                 }
  425.  
  426.                 return (kpm / count);
  427.             }
  428.  
  429.  
  430.             public double getRoundKills()
  431.             {
  432.                 int count = getCount();
  433.                 if (count == 0)
  434.                     return 0;
  435.  
  436.                 double kills = 0;
  437.                 foreach (PlayerProfile player in getMembers())
  438.                 {
  439.                     kills += player.getRoundKills();
  440.                 }
  441.  
  442.                 return (kills / count);
  443.             }
  444.  
  445.             public double getRoundDeaths()
  446.             {
  447.                 int count = getCount();
  448.                 if (count == 0)
  449.                     return 0;
  450.  
  451.                 double deaths = 0;
  452.                 foreach (PlayerProfile player in getMembers())
  453.                 {
  454.                     deaths += player.getRoundDeaths();
  455.                 }
  456.  
  457.                 return (deaths / count);
  458.             }
  459.  
  460.             public double getRoundScore()
  461.             {
  462.                 int count = getCount();
  463.                 if (count == 0)
  464.                     return 0;
  465.  
  466.                 double score = 0;
  467.                 foreach (PlayerProfile player in getMembers())
  468.                 {
  469.                     score += player.getRoundScore();
  470.                 }
  471.  
  472.                 return (score / count);
  473.             }
  474.  
  475.  
  476.             public double getRoundKdr()
  477.             {
  478.                 return (getRoundKills() + 1) / (getRoundDeaths() + 1);
  479.             }
  480.  
  481.             public DateTime getRoundTime()
  482.             {
  483.                 int count = getCount();
  484.                 if (count == 0)
  485.                     return DateTime.Now;
  486.  
  487.                 long total_ticks = 0;
  488.                 foreach (PlayerProfile player in getMembers())
  489.                 {
  490.                     total_ticks += player.getRoundTime().Ticks;
  491.                 }
  492.  
  493.                 long avg = total_ticks / count;
  494.                 return new DateTime(avg);
  495.             }
  496.  
  497.             public override String ToString()
  498.             {
  499.                 return "Team(" + TN(getTeamId()) + ").Squad(" + SQN(getSquadId()) + "): " + getMembersListStr();
  500.             }
  501.  
  502.             public string getMembersListStr()
  503.             {
  504.                 List<string> names = new List<string>();
  505.                 foreach (PlayerProfile player in members)
  506.                     names.Add(player.ToString());
  507.  
  508.                 return String.Join(", ", names.ToArray());
  509.             }
  510.  
  511.  
  512.             public string getClanTag()
  513.             {
  514.                 if (getCount() == 0)
  515.                     return "";
  516.  
  517.                 return getRandomPlayer().getClanTag();
  518.             }
  519.  
  520.             public string getMajorityClanTag()
  521.             {
  522.  
  523.                 if (getCount() == 0)
  524.                     return "";
  525.  
  526.                 Dictionary<string, int> tagCount = new Dictionary<string, int>();
  527.                 string tag = "";
  528.  
  529.                 /* count how many times each tag repeats */
  530.                 foreach (PlayerProfile player in getMembers())
  531.                 {
  532.                     tag = player.getClanTag();
  533.                     if (tag == null || tag.Length == 0)
  534.                         continue;
  535.  
  536.                     if (!tagCount.ContainsKey(tag))
  537.                         tagCount[tag] = 0;
  538.  
  539.                     tagCount[tag]++;
  540.                 }
  541.  
  542.                 if (tagCount.Count == 0)
  543.                     return "";
  544.  
  545.                 /* sort by ascending tag count */
  546.                 List<KeyValuePair<string, int>> list = new List<KeyValuePair<string, int>>(tagCount);
  547.                 list.Sort(delegate(KeyValuePair<string, int> left, KeyValuePair<string, int> right) { return left.Value.CompareTo(right.Value) * (-1); });
  548.  
  549.                 return list[0].Key;
  550.             }
  551.  
  552.             public void setSquadId(int sid)
  553.             {
  554.                 squadId = sid;
  555.             }
  556.  
  557.             public void setTeamId(int tid)
  558.             {
  559.                 teamId = tid;
  560.             }
  561.         }
  562.  
  563.         private class PlayerMessage
  564.         {
  565.             public MessageType type;
  566.             public string text;
  567.             public int time;
  568.  
  569.             public PlayerMessage(string tx)
  570.             {
  571.                 text = tx;
  572.                 type = MessageType.say;
  573.             }
  574.         }
  575.  
  576.         public enum PluginState { stop, wait, check, warn, balance };
  577.  
  578.         //variables to keep track of the start time for each state
  579.         DateTime startStopTime;
  580.         DateTime startWaitTime;
  581.         DateTime startCheckTime;
  582.         DateTime startWarnTime;
  583.         DateTime startBalanceTime;
  584.         DateTime startRoundTime;
  585.         DateTime utc; //universal time;
  586.  
  587.         PluginState pluginState;
  588.         CServerInfo serverInfo = null;
  589.  
  590.         bool plugin_enabled = false;
  591.  
  592.         public Dictionary<String, String> maps;
  593.         public Dictionary<String, String> modes;
  594.         public Dictionary<String, List<String>> settings_group;
  595.         public Dictionary<String, int> settings_group_order;
  596.         public Dictionary<string, bool> booleanVariables;
  597.         public Dictionary<string, int> integerVariables;
  598.         public Dictionary<string, float> floatVariables;
  599.         public Dictionary<string, string> stringListVariables;
  600.         public Dictionary<string, string> stringVariables;
  601.         public List<string> hiddenVariables;
  602.  
  603.  
  604.         public delegate bool integerVariableValidator(string var, int value);
  605.         public delegate bool booleanVariableValidator(string var, bool value);
  606.         private delegate int player_sort_method(PlayerProfile left, PlayerProfile right);
  607.         private delegate int squad_sort_method(PlayerSquad left, PlayerSquad right);
  608.         public delegate bool stringVariableValidator(string var, string value);
  609.         public Dictionary<string, integerVariableValidator> integerVarValidators;
  610.         public Dictionary<string, booleanVariableValidator> booleanVarValidators;
  611.         public Dictionary<string, stringVariableValidator> stringVarValidators;
  612.  
  613.  
  614.         private Dictionary<string, PlayerProfile> players;
  615.  
  616.  
  617.         public enum PlayerState { dead, alive, left, kicked, limbo };
  618.         public enum MessageType { say, invalid };
  619.  
  620.  
  621.         private struct PlayerStats
  622.         {
  623.             public double rank;
  624.             public double kills;
  625.             public double deaths;
  626.             public double score;
  627.             public double skill;
  628.  
  629.             public void reset()
  630.             {
  631.                 rank = 0;
  632.                 kills = 0;
  633.                 deaths = 0;
  634.                 score = 0;
  635.                 skill = 0;
  636.             }
  637.  
  638.             public double kdr()
  639.             {
  640.                 return (kills + 1) / (deaths + 1);
  641.             }
  642.         }
  643.  
  644.         private class PlayerProfile
  645.         {
  646.             private InsaneBalancer plugin;
  647.             public string name;
  648.             public string tag = "";
  649.             public PlayerStats stats;
  650.             public PlayerStats round_stats;
  651.             public PlayerState state;
  652.             public CPlayerInfo info;
  653.             public CPunkbusterInfo pbinfo;
  654.             public Queue<PlayerMessage> qmsg;          //queued messages
  655.             public DateTime time = DateTime.Now;
  656.             public DateTime last_kill = DateTime.Now;
  657.             public DateTime last_death = DateTime.Now;
  658.             public DateTime last_spawn = DateTime.Now;
  659.             public DateTime last_chat = DateTime.Now;
  660.             public DateTime last_score = DateTime.Now;
  661.  
  662.             public bool visited = false;
  663.             public bool vacated = false;
  664.  
  665.             int savedTeamId = -1;
  666.             int savedSquadId = -1;
  667.  
  668.             int targetTeamId = -1;
  669.             int targetSquadId = -1;
  670.  
  671.             int delayedTeamId = -1;
  672.             int delayedSquadId = -1;
  673.  
  674.  
  675.  
  676.  
  677.             public bool isInGame()
  678.             {
  679.                 return (info.TeamID >= 0);
  680.             }
  681.  
  682.             public PlayerProfile(PlayerProfile player)
  683.             {
  684.                 /* shallow copy */
  685.                 updateInfo(player.info);
  686.                 pbinfo = player.pbinfo;
  687.                 name = player.name;
  688.                 plugin = player.plugin;
  689.                 stats = player.stats;
  690.                 state = player.state;
  691.                 qmsg = player.qmsg;
  692.                 tag = player.tag;
  693.                 time = player.time;
  694.             }
  695.  
  696.             public PlayerProfile(InsaneBalancer plg, CPunkbusterInfo inf)
  697.             {
  698.                 info = new CPlayerInfo();
  699.                 pbinfo = inf;
  700.                 name = pbinfo.SoldierName;
  701.                 plugin = plg;
  702.                 time = DateTime.Now;
  703.                 resetStats();
  704.                 fetchClanTag();
  705.             }
  706.  
  707.             public void fetchClanTag()
  708.             {
  709.                 tag = plugin.blog.getPlayerTag(name);
  710.             }
  711.  
  712.  
  713.             public void updateInfo(CPlayerInfo inf)
  714.             {
  715.                 /* don't update the information while round is begining */
  716.                 if (plugin.round_balancer)
  717.                     return;
  718.  
  719.                 if (plugin.live_balancer)
  720.                     return;
  721.  
  722.  
  723.                 if (info.Score != inf.Score)
  724.                     updateLastScore();
  725.  
  726.                 info = inf;
  727.  
  728.                 round_stats.kills = info.Kills;
  729.                 round_stats.deaths = info.Deaths;
  730.                 round_stats.score = info.Score;
  731.             }
  732.  
  733.  
  734.             public void resetStats()
  735.             {
  736.                 //queued messages
  737.                 qmsg = new Queue<PlayerMessage>();
  738.  
  739.                 //other
  740.                 state = PlayerState.limbo;
  741.                 round_stats.reset();
  742.  
  743.                 savedSquadId = -1;
  744.                 savedTeamId = -1;
  745.                 targetSquadId = -1;
  746.                 targetTeamId = -1;
  747.                 delayedTeamId = -1;
  748.                 delayedSquadId = -1;
  749.  
  750.                 last_kill = DateTime.Now;
  751.                 last_chat = DateTime.Now;
  752.                 last_death = DateTime.Now;
  753.                 last_spawn = DateTime.Now;
  754.                 last_score = DateTime.Now;
  755.             }
  756.  
  757.  
  758.             /* Player Messages */
  759.             public void dequeueMessages()
  760.             {
  761.                 while (this.qmsg.Count > 0)
  762.                 {
  763.                     PlayerMessage msg = this.qmsg.Dequeue();
  764.                     if (msg.type.Equals(MessageType.say))
  765.                     {
  766.                         this.plugin.SendPlayerMessage(name, msg.text);
  767.                     }
  768.                 }
  769.             }
  770.  
  771.  
  772.             public void enqueueMessage(PlayerMessage msg)
  773.             {
  774.                 this.qmsg.Enqueue(msg);
  775.             }
  776.  
  777.  
  778.             public bool willMoveAcrossTeams()
  779.             {
  780.                 return willMoveTeams();
  781.             }
  782.  
  783.  
  784.             public bool willMoveAcrossSquad()
  785.             {
  786.                 return !willMoveAcrossTeams() && willMoveSquads();
  787.             }
  788.  
  789.             public bool willMoveTeams()
  790.             {
  791.                 return getSavedSquadId() != getTargetTeamId();
  792.             }
  793.  
  794.             public bool willMoveSquads()
  795.             {
  796.                 return getSavedSquadId() != getTargetSquadId();
  797.             }
  798.  
  799.  
  800.             /* Round Level Statistics */
  801.             public double getRoundKpm()
  802.             {
  803.                 double minutes = plugin.getRoundMinutes();
  804.                 double kills = getRoundKills();
  805.  
  806.                 return kills / minutes;
  807.             }
  808.  
  809.             public double getRoundSpm()
  810.             {
  811.                 double minutes = plugin.getRoundMinutes();
  812.                 double score = getRoundScore();
  813.                 return score / minutes;
  814.             }
  815.  
  816.             public double getRoundKills()
  817.             {
  818.                 return round_stats.kills;
  819.             }
  820.  
  821.             public double getRoundScore()
  822.             {
  823.                 return round_stats.score;
  824.             }
  825.  
  826.             public double getRoundDeaths()
  827.             {
  828.                 return round_stats.deaths;
  829.             }
  830.  
  831.             public double getRoundKdr()
  832.             {
  833.                 return (getRoundKills() + 1) / (getRoundDeaths() + 1);
  834.  
  835.             }
  836.  
  837.             public DateTime getRoundTime()
  838.             {
  839.                 return time;
  840.             }
  841.  
  842.             public override string ToString()
  843.             {
  844.                 string t = getClanTag();
  845.                 if (t.Length > 0)
  846.                     return "[" + t + "]" + name;
  847.                 return name;
  848.             }
  849.  
  850.  
  851.             /* Player State and Information */
  852.             public bool isAlive()
  853.             {
  854.                 return state.Equals(PlayerState.alive);
  855.             }
  856.  
  857.             public bool isDead()
  858.             {
  859.                 return state.Equals(PlayerState.dead);
  860.             }
  861.  
  862.             public bool wasKicked()
  863.             {
  864.                 return state.Equals(PlayerState.kicked);
  865.             }
  866.  
  867.             public bool leftGame()
  868.             {
  869.                 return state.Equals(PlayerState.left);
  870.             }
  871.  
  872.  
  873.             public string getClanTag()
  874.             {
  875.                 return tag.ToLower();
  876.             }
  877.  
  878.             public bool isInClan()
  879.             {
  880.                 return getClanTag().Length > 0;
  881.             }
  882.  
  883.             public int getLastScore()
  884.             {
  885.                 return (int)DateTime.Now.Subtract(last_score).TotalSeconds;
  886.             }
  887.  
  888.             public int getLastChat()
  889.             {
  890.                 return (int) DateTime.Now.Subtract(last_chat).TotalSeconds;
  891.             }
  892.  
  893.             public void updateLastScore()
  894.             {
  895.                 last_score = DateTime.Now;
  896.             }
  897.  
  898.             public void updateLastChat()
  899.             {
  900.                 last_chat = DateTime.Now;
  901.             }
  902.  
  903.             public int getLastKill()
  904.             {
  905.                 return (int) DateTime.Now.Subtract(last_kill).TotalSeconds;
  906.             }
  907.  
  908.             public void updateLastKill()
  909.             {
  910.                 last_kill = DateTime.Now;
  911.             }
  912.  
  913.             public int getLastDeath()
  914.             {
  915.                 return (int) DateTime.Now.Subtract(last_death).TotalSeconds;
  916.             }
  917.  
  918.             public void updateLastDeath()
  919.             {
  920.                 last_death = DateTime.Now;
  921.             }
  922.  
  923.  
  924.             public int getLastSpawn()
  925.             {
  926.                 return (int) DateTime.Now.Subtract(last_spawn).TotalSeconds;
  927.             }
  928.  
  929.             public void updateLastSpawn()
  930.             {
  931.                 last_spawn = DateTime.Now;
  932.             }
  933.  
  934.            
  935.  
  936.             public virtual void setSquadId(int sid)
  937.             {
  938.                 info.SquadID = sid;
  939.             }
  940.  
  941.             public virtual void setTeamId(int tid)
  942.             {
  943.                 info.TeamID = tid;
  944.             }
  945.  
  946.             public virtual int getSquadId()
  947.             {
  948.                 return info.SquadID;
  949.             }
  950.  
  951.             public virtual int getTeamId()
  952.             {
  953.                 return info.TeamID;
  954.             }
  955.  
  956.             public void saveTeamSquad()
  957.             {
  958.  
  959.                 if (savedTeamId == -1)
  960.                     savedTeamId = getTeamId();
  961.  
  962.                 if (savedSquadId == -1)
  963.                     savedSquadId = getSquadId();
  964.             }
  965.  
  966.             public void saveTargetTeamSquad()
  967.             {
  968.  
  969.                 if (targetTeamId == -1)
  970.                     targetTeamId = getTeamId();
  971.  
  972.                 if (targetSquadId == -1)
  973.                     targetSquadId = getSquadId();
  974.             }
  975.  
  976.             public void saveDelayedTeamSquad()
  977.             {
  978.                 if (delayedTeamId == -1)
  979.                     delayedTeamId = getTeamId();
  980.  
  981.                 if (delayedSquadId == -1)
  982.                     delayedSquadId = getSquadId();
  983.             }
  984.  
  985.             public void resetDelayedTeamSquad()
  986.             {
  987.                 delayedTeamId = -1;
  988.                 delayedSquadId = -1;
  989.             }
  990.  
  991.             public void resetSavedTeamSquad()
  992.             {
  993.                 savedTeamId = -1;
  994.                 savedSquadId = -1;
  995.             }
  996.  
  997.             public int getSavedSquadId()
  998.             {
  999.                 return savedSquadId;
  1000.             }
  1001.  
  1002.             public int getSavedTeamId()
  1003.             {
  1004.                 return savedTeamId;
  1005.             }
  1006.  
  1007.             public int getTargetSquadId()
  1008.             {
  1009.                 return targetSquadId;
  1010.             }
  1011.  
  1012.             public int getTargetTeamId()
  1013.             {
  1014.                 return targetTeamId;
  1015.             }
  1016.  
  1017.             public int getDelayedTeamId()
  1018.             {
  1019.                 return delayedTeamId;
  1020.             }
  1021.  
  1022.  
  1023.             public int getDelayedSquadId()
  1024.             {
  1025.                 return delayedSquadId;
  1026.             }
  1027.  
  1028.  
  1029.             public void resetTeamSquad()
  1030.             {
  1031.                 if (savedTeamId > 0)
  1032.                     setTeamId(savedTeamId);
  1033.  
  1034.                 if (savedSquadId > 0)
  1035.                     setSquadId(savedSquadId);
  1036.             }
  1037.  
  1038.  
  1039.             public string getRoundStatistics()
  1040.             {
  1041.                 return String.Format("score({0}), kills({1}), deaths({2}) kdr({3}), spm({4}), kpm({5}), time({6})", getRoundScore(), getRoundKills(), getRoundDeaths(), Math.Round(getRoundKdr(), 2), Math.Round(getRoundSpm(), 2), Math.Round(getRoundKpm(), 2), getRoundTime());
  1042.             }
  1043.  
  1044.             public string getIdleStatistics()
  1045.             {
  1046.                 return String.Format("last_kill({0}), last_death({1}), last_spawn({2}) last_chat({3}) last_score({4})", getLastKill(), getLastDeath(), getLastSpawn(), getLastChat(), getLastScore());
  1047.             }
  1048.  
  1049.         }
  1050.  
  1051.  
  1052.         public InsaneBalancer()
  1053.         {
  1054.             utc = DateTime.Now;
  1055.             startRoundTime = utc;
  1056.             blog = new BattleLog(this);
  1057.  
  1058.             this.maps = new Dictionary<string, string>();
  1059.             maps.Add("mp_001", "grand_bazaar");
  1060.             maps.Add("mp_003", "teheran_highway");
  1061.             maps.Add("mp_007", "caspian_border");
  1062.             maps.Add("mp_011", "seine_crossing");
  1063.             maps.Add("mp_012", "operation_firestorm");
  1064.             maps.Add("mp_013", "damavand_peak");
  1065.             maps.Add("mp_017", "noshahar_canals");
  1066.             maps.Add("mp_018", "kharg_island");
  1067.             maps.Add("mp_subway", "operation_metro");
  1068.  
  1069.             this.modes = new Dictionary<string, string>();
  1070.             modes.Add("conquestlarge0", "cl");
  1071.             modes.Add("conquestsmall0", "cs");
  1072.             modes.Add("rushlarge0", "rl");
  1073.             modes.Add("teamdeathmatch0", "td");
  1074.             modes.Add("squadrush0", "sr");
  1075.  
  1076.  
  1077.  
  1078.  
  1079.             this.players = new Dictionary<string, PlayerProfile>();
  1080.  
  1081.             this.booleanVariables = new Dictionary<string, bool>();
  1082.             this.booleanVariables.Add("auto_start", true);
  1083.             this.booleanVariables.Add("keep_squads_live", true);
  1084.             this.booleanVariables.Add("keep_squads_round", true);
  1085.             this.booleanVariables.Add("keep_clans_live", false);
  1086.             this.booleanVariables.Add("keep_clans_round", false);
  1087.             this.booleanVariables.Add("use_white_list", false);
  1088.             this.booleanVariables.Add("use_extra_white_lists", false);
  1089.             this.booleanVariables.Add("virtual_mode", false);
  1090.             this.booleanVariables.Add("warn_say", true);
  1091.             this.booleanVariables.Add("balance_round", true);
  1092.             this.booleanVariables.Add("balance_live", true);
  1093.             this.booleanVariables.Add("kick_idle", true);
  1094.             this.booleanVariables.Add("wait_death", false);
  1095.  
  1096.  
  1097.             this.booleanVariables.Add("quiet_mode", false);
  1098.             this.booleanVariables.Add("advanced_mode", false);
  1099.  
  1100.  
  1101.  
  1102.             this.integerVariables = new Dictionary<string, int>();
  1103.             this.integerVariables.Add("balance_threshold", 1);
  1104.             this.integerVariables.Add("debug_level", 3);
  1105.             this.integerVariables.Add("live_interval_time", 15);
  1106.             this.integerVariables.Add("round_interval", 1);
  1107.             this.integerVariables.Add("round_wait_time", 3);
  1108.             this.integerVariables.Add("warn_msg_interval_time", 15);
  1109.             this.integerVariables.Add("warn_msg_total_time", 15);
  1110.             this.integerVariables.Add("warn_msg_countdown_time", 3);
  1111.             this.integerVariables.Add("warn_msg_display_time", 5);
  1112.  
  1113.             this.integerVariables.Add("last_kill_time", 300);
  1114.             this.integerVariables.Add("last_death_time", 300);
  1115.             this.integerVariables.Add("last_spawn_time", 300);
  1116.             this.integerVariables.Add("last_chat_time", 300);
  1117.             this.integerVariables.Add("last_score_time", 300);
  1118.  
  1119.  
  1120.  
  1121.             this.integerVarValidators = new Dictionary<string, integerVariableValidator>();
  1122.             this.integerVarValidators.Add("warn_msg_interval_time", integerValidator);
  1123.             this.integerVarValidators.Add("warn_msg_total_time", integerValidator);
  1124.             this.integerVarValidators.Add("warn_msg_display_time", integerValidator);
  1125.             this.integerVarValidators.Add("warn_msg_countdown_time", integerValidator);
  1126.             this.integerVarValidators.Add("balance_threshold", integerValidator);
  1127.             this.integerVarValidators.Add("round_interval", integerValidator);
  1128.             this.integerVarValidators.Add("live_interval_time", integerValidator);
  1129.             this.integerVarValidators.Add("debug_level", integerValidator);
  1130.             this.integerVarValidators.Add("last_kill_time", integerValidator);
  1131.             this.integerVarValidators.Add("last_death_time", integerValidator);
  1132.             this.integerVarValidators.Add("last_spawn_time", integerValidator);
  1133.             this.integerVarValidators.Add("last_chat_time", integerValidator);
  1134.             this.integerVarValidators.Add("last_score_time", integerValidator);
  1135.  
  1136.             /* set up per-map intervals */
  1137.             List<String> map_interval = new List<string>();
  1138.             foreach (KeyValuePair<String, String> mode_pair in modes)
  1139.                 foreach (KeyValuePair<String, String> map_pair in maps)
  1140.                     map_interval.Add(mode_pair.Value + "_" + map_pair.Value);
  1141.  
  1142.             foreach (String name in map_interval)
  1143.             {
  1144.                 this.integerVariables.Add(name, 0);
  1145.                 this.integerVarValidators.Add(name, integerValidator);
  1146.             }
  1147.  
  1148.  
  1149.             this.booleanVarValidators = new Dictionary<string, booleanVariableValidator>();
  1150.             this.booleanVarValidators.Add("keep_squads_live", booleanValidator);
  1151.             this.booleanVarValidators.Add("keep_squads_round", booleanValidator);
  1152.             this.booleanVarValidators.Add("keep_clan_live", booleanValidator);
  1153.             this.booleanVarValidators.Add("keep_clans_round", booleanValidator);
  1154.             this.booleanVarValidators.Add("use_white_list", booleanValidator);
  1155.             this.booleanVarValidators.Add("use_extra_white_lists", booleanValidator);
  1156.             this.booleanVarValidators.Add("virtual_mode", booleanValidator);
  1157.             this.booleanVarValidators.Add("kick_idle", booleanValidator);
  1158.             this.booleanVarValidators.Add("wait_death", booleanValidator);
  1159.  
  1160.             this.stringVarValidators = new Dictionary<string, stringVariableValidator>();
  1161.             this.stringVarValidators.Add("round_sort", stringValidator);
  1162.             this.stringVarValidators.Add("live_sort", stringValidator);
  1163.             this.stringVarValidators.Add("console", commandValidator);
  1164.  
  1165.  
  1166.             this.floatVariables = new Dictionary<string, float>();
  1167.             this.stringListVariables = new Dictionary<string, string>();
  1168.             this.stringListVariables.Add("admin_list", @"micovery, admin2, admin3");
  1169.  
  1170.             this.stringListVariables.Add("player_kick_wlist", "list of players that should not kicked when idle");
  1171.             this.stringListVariables.Add("player_move_wlist", "list of players that should not be moved");
  1172.             this.stringListVariables.Add("player_safe_wlist", "list of players that should not be kicked or moved ");
  1173.             this.stringListVariables.Add("clan_kick_wlist", "list of clans that should not be kicked when idle");
  1174.             this.stringListVariables.Add("clan_move_wlist", "list of clans that should not be moved");
  1175.             this.stringListVariables.Add("clan_safe_wlist", "list of clans that should not be kicked or moved");
  1176.  
  1177.  
  1178.             this.stringVariables = new Dictionary<string, string>();
  1179.  
  1180.             this.stringVariables.Add("round_sort", "spm_desc_round");
  1181.             this.stringVariables.Add("live_sort", "time_desc_round");
  1182.             this.stringVariables.Add("mail", "");
  1183.             this.stringVariables.Add("pass", "");
  1184.             this.stringVariables.Add("console", "Type a command here to test");
  1185.  
  1186.             this.hiddenVariables = new List<string>();
  1187.             this.hiddenVariables.Add("advanced_mode");
  1188.             this.hiddenVariables.Add("warn_msg_total_time");
  1189.             this.hiddenVariables.Add("warn_msg_countdown_time");
  1190.             this.hiddenVariables.Add("warn_msg_interval_time");
  1191.             this.hiddenVariables.Add("warn_msg_display_time");
  1192.             this.hiddenVariables.Add("quiet_mode");
  1193.             this.hiddenVariables.Add("auto_start");
  1194.             this.hiddenVariables.Add("virtual_mode");
  1195.  
  1196.             /* Grouping settings */
  1197.  
  1198.             this.settings_group = new Dictionary<string, List<string>>();
  1199.  
  1200.  
  1201.             List<String> battle_log_group = new List<string>();
  1202.             battle_log_group.Add("mail");
  1203.             battle_log_group.Add("pass");
  1204.  
  1205.             List<String> whitelist_group = new List<string>();
  1206.             whitelist_group.Add("use_extra_white_lists");
  1207.             whitelist_group.Add("player_move_wlist");
  1208.             whitelist_group.Add("player_kick_wlist");
  1209.             whitelist_group.Add("player_safe_wlist");
  1210.            
  1211.             whitelist_group.Add("clan_move_wlist");
  1212.             whitelist_group.Add("clan_kick_wlist");
  1213.             whitelist_group.Add("clan_safe_wlist");
  1214.  
  1215.             List<String> round_balancer_group = new List<string>();
  1216.             round_balancer_group.Add("keep_clans_round");
  1217.             round_balancer_group.Add("keep_squads_round");
  1218.             round_balancer_group.Add("round_interval");
  1219.             round_balancer_group.Add("round_wait_time");
  1220.             round_balancer_group.Add("round_sort");
  1221.             round_balancer_group.Add("kick_idle");
  1222.  
  1223.             List<String> idle_watch_group = new List<string>();
  1224.             idle_watch_group.Add("last_kill_time");
  1225.             idle_watch_group.Add("last_death_time");
  1226.             idle_watch_group.Add("last_spawn_time");
  1227.             idle_watch_group.Add("last_chat_time");
  1228.             idle_watch_group.Add("last_score_time");
  1229.  
  1230.             List<String> live_balancer_group = new List<string>();
  1231.             live_balancer_group.Add("keep_clans_live");
  1232.             live_balancer_group.Add("keep_squads_live");
  1233.             live_balancer_group.Add("live_sort");
  1234.             live_balancer_group.Add("live_interval_time");
  1235.             live_balancer_group.Add("warn_say");
  1236.             live_balancer_group.Add("wait_death");
  1237.             live_balancer_group.Add("balance_threshold");
  1238.  
  1239.             settings_group.Add("Round Interval", map_interval);
  1240.             settings_group.Add("Battlelog", battle_log_group);
  1241.             settings_group.Add("Whitelist", whitelist_group);
  1242.             settings_group.Add("Live Balancer", live_balancer_group);
  1243.             settings_group.Add("Round Balancer", round_balancer_group);
  1244.             settings_group.Add("Idle Watch", idle_watch_group);
  1245.  
  1246.             settings_group_order = new Dictionary<string, int>();
  1247.             settings_group_order.Add("Battlelog", 1);
  1248.             settings_group_order.Add("Settings", 2);
  1249.             settings_group_order.Add("Live Balancer", 3);
  1250.             settings_group_order.Add("Round Balancer", 4);
  1251.             settings_group_order.Add("Whitelist", 5);
  1252.             settings_group_order.Add("Idle Watch", 6);
  1253.             settings_group_order.Add("Round Interval", 7);
  1254.  
  1255.         }
  1256.  
  1257.  
  1258.  
  1259.         public void loadSettings()
  1260.         {
  1261.             attempts = 0;
  1262.         }
  1263.  
  1264.  
  1265.         private player_sort_method getPlayerSort(string phase)
  1266.         {
  1267.             string sort_method = getStringVarValue(phase);
  1268.  
  1269.  
  1270.             if (sort_method.CompareTo("kdr_asc_round") == 0)
  1271.                 return player_kdr_asc_round_cmp;
  1272.             else if (sort_method.CompareTo("kdr_desc_round") == 0)
  1273.                 return player_kdr_desc_round_cmp;
  1274.             else if (sort_method.CompareTo("score_asc_round") == 0)
  1275.                 return player_score_asc_round_cmp;
  1276.             else if (sort_method.CompareTo("score_desc_round") == 0)
  1277.                 return player_score_desc_round_cmp;
  1278.             else if (sort_method.CompareTo("spm_asc_round") == 0)
  1279.                 return player_spm_asc_round_cmp;
  1280.             else if (sort_method.CompareTo("spm_desc_round") == 0)
  1281.                 return player_spm_desc_round_cmp;
  1282.             else if (sort_method.CompareTo("kpm_asc_round") == 0)
  1283.                 return player_kpm_asc_round_cmp;
  1284.             else if (sort_method.CompareTo("kpm_desc_round") == 0)
  1285.                 return player_kpm_desc_round_cmp;
  1286.             else if (sort_method.CompareTo("time_asc_round") == 0)
  1287.                 return player_time_asc_round_cmp;
  1288.             else if (sort_method.CompareTo("time_desc_round") == 0)
  1289.                 return player_time_desc_round_cmp;
  1290.  
  1291.             ConsoleWrite("cannot find player sort method for ^b" + sort_method + "^0 during ^b" + phase + "^n, using default sort");
  1292.             return player_spm_asc_round_cmp;
  1293.         }
  1294.  
  1295.  
  1296.         private squad_sort_method getSquadSort(string phase)
  1297.         {
  1298.             string sort_method = getStringVarValue(phase);
  1299.  
  1300.             if (sort_method.CompareTo("kdr_asc_round") == 0)
  1301.                 return squad_kdr_asc_round_cmp;
  1302.             else if (sort_method.CompareTo("kdr_desc_round") == 0)
  1303.                 return squad_kdr_desc_round_cmp;
  1304.             else if (sort_method.CompareTo("score_asc_round") == 0)
  1305.                 return squad_score_asc_round_cmp;
  1306.             else if (sort_method.CompareTo("score_desc_round") == 0)
  1307.                 return squad_score_desc_round_cmp;
  1308.             else if (sort_method.CompareTo("spm_asc_round") == 0)
  1309.                 return squad_spm_asc_round_cmp;
  1310.             else if (sort_method.CompareTo("spm_desc_round") == 0)
  1311.                 return squad_spm_desc_round_cmp;
  1312.             else if (sort_method.CompareTo("kpm_asc_round") == 0)
  1313.                 return squad_kpm_asc_round_cmp;
  1314.             else if (sort_method.CompareTo("kpm_desc_round") == 0)
  1315.                 return squad_kpm_desc_round_cmp;
  1316.             else if (sort_method.CompareTo("time_asc_round") == 0)
  1317.                 return squad_time_asc_round_cmp;
  1318.             else if (sort_method.CompareTo("time_desc_round") == 0)
  1319.                 return squad_time_desc_round_cmp;
  1320.  
  1321.             ConsoleWrite("cannot find squad sort method for ^b" + sort_method + "^0 during ^b" + phase + "^n, using default sort");
  1322.             return squad_kpm_desc_round_cmp;
  1323.         }
  1324.  
  1325.  
  1326.         /* squad comparison methods */
  1327.  
  1328.         private int squad_count_asc_cmp(PlayerSquad left, PlayerSquad right)
  1329.         {
  1330.             int lval = left.getCount();
  1331.             int rval = right.getCount();
  1332.  
  1333.             return lval.CompareTo(rval);
  1334.         }
  1335.  
  1336.         private int squad_count_desc_cmp(PlayerSquad left, PlayerSquad right)
  1337.         {
  1338.             return squad_count_asc_cmp(left, right) * (-1);
  1339.         }
  1340.  
  1341.  
  1342.         private int squad_kdr_asc_round_cmp(PlayerSquad left, PlayerSquad right)
  1343.         {
  1344.             double lval = left.getRoundKdr();
  1345.             double rval = right.getRoundKdr();
  1346.             return lval.CompareTo(rval);
  1347.         }
  1348.  
  1349.         private int squad_kdr_desc_round_cmp(PlayerSquad left, PlayerSquad right)
  1350.         {
  1351.             return squad_kdr_asc_round_cmp(left, right) * (-1);
  1352.         }
  1353.  
  1354.         private int squad_spm_asc_round_cmp(PlayerSquad left, PlayerSquad right)
  1355.         {
  1356.             double lval = left.getRoundSpm();
  1357.             double rval = right.getRoundSpm();
  1358.             return lval.CompareTo(rval);
  1359.         }
  1360.  
  1361.         private int squad_spm_desc_round_cmp(PlayerSquad left, PlayerSquad right)
  1362.         {
  1363.             return squad_spm_asc_round_cmp(left, right) * (-1);
  1364.         }
  1365.  
  1366.  
  1367.         private int squad_score_asc_round_cmp(PlayerSquad left, PlayerSquad right)
  1368.         {
  1369.             double lval = left.getRoundScore();
  1370.             double rval = right.getRoundScore();
  1371.             return lval.CompareTo(rval);
  1372.         }
  1373.  
  1374.         private int squad_score_desc_round_cmp(PlayerSquad left, PlayerSquad right)
  1375.         {
  1376.             return squad_score_asc_round_cmp(left, right) * (-1);
  1377.         }
  1378.  
  1379.         private int squad_kpm_asc_round_cmp(PlayerSquad left, PlayerSquad right)
  1380.         {
  1381.             double lval = left.getRoundKpm();
  1382.             double rval = right.getRoundKpm();
  1383.             return lval.CompareTo(rval);
  1384.         }
  1385.  
  1386.         private int squad_kpm_desc_round_cmp(PlayerSquad left, PlayerSquad right)
  1387.         {
  1388.             return squad_kpm_asc_round_cmp(left, right) * (-1);
  1389.         }
  1390.  
  1391.  
  1392.         private int squad_time_asc_round_cmp(PlayerSquad left, PlayerSquad right)
  1393.         {
  1394.             DateTime lval = left.getRoundTime();
  1395.             DateTime rval = right.getRoundTime();
  1396.             return lval.CompareTo(rval);
  1397.         }
  1398.  
  1399.         private int squad_time_desc_round_cmp(PlayerSquad left, PlayerSquad right)
  1400.         {
  1401.             return squad_time_asc_round_cmp(left, right) * (-1);
  1402.         }
  1403.  
  1404.  
  1405.  
  1406.  
  1407.         /* player comparison methods */
  1408.  
  1409.  
  1410.         private int player_kdr_asc_round_cmp(PlayerProfile left, PlayerProfile right)
  1411.         {
  1412.             double lval = left.getRoundKdr();
  1413.             double rval = right.getRoundKdr();
  1414.  
  1415.             return lval.CompareTo(rval);
  1416.         }
  1417.  
  1418.         private int player_kdr_desc_round_cmp(PlayerProfile left, PlayerProfile right)
  1419.         {
  1420.             return player_kdr_asc_round_cmp(left, right) * (-1);
  1421.         }
  1422.  
  1423.         private int player_spm_asc_round_cmp(PlayerProfile left, PlayerProfile right)
  1424.         {
  1425.             double lval = left.getRoundSpm();
  1426.             double rval = right.getRoundSpm();
  1427.             return lval.CompareTo(rval);
  1428.         }
  1429.  
  1430.         private int player_spm_desc_round_cmp(PlayerProfile left, PlayerProfile right)
  1431.         {
  1432.             return player_spm_asc_round_cmp(left, right) * (-1);
  1433.         }
  1434.  
  1435.  
  1436.         private int player_score_asc_round_cmp(PlayerProfile left, PlayerProfile right)
  1437.         {
  1438.             double lval = left.getRoundScore();
  1439.             double rval = right.getRoundScore();
  1440.             return lval.CompareTo(rval);
  1441.         }
  1442.  
  1443.         private int player_score_desc_round_cmp(PlayerProfile left, PlayerProfile right)
  1444.         {
  1445.             return player_score_asc_round_cmp(left, right) * (-1);
  1446.         }
  1447.  
  1448.         private int player_kpm_asc_round_cmp(PlayerProfile left, PlayerProfile right)
  1449.         {
  1450.             double lval = left.getRoundKpm();
  1451.             double rval = right.getRoundKpm();
  1452.             return lval.CompareTo(rval);
  1453.         }
  1454.  
  1455.         private int player_kpm_desc_round_cmp(PlayerProfile left, PlayerProfile right)
  1456.         {
  1457.             return player_kpm_asc_round_cmp(left, right) * (-1);
  1458.         }
  1459.  
  1460.  
  1461.         private int player_time_asc_round_cmp(PlayerProfile left, PlayerProfile right)
  1462.         {
  1463.             DateTime lval = left.getRoundTime();
  1464.             DateTime rval = right.getRoundTime();
  1465.             return lval.CompareTo(rval);
  1466.         }
  1467.  
  1468.         private int player_time_desc_round_cmp(PlayerProfile left, PlayerProfile right)
  1469.         {
  1470.             return player_time_asc_round_cmp(left, right) * (-1);
  1471.         }
  1472.  
  1473.  
  1474.  
  1475.         public void unloadSettings()
  1476.         {
  1477.             this.players.Clear();
  1478.             removeTask("InsaneBalancer");
  1479.             attempts = 0;
  1480.         }
  1481.  
  1482.  
  1483.  
  1484.         public string GetPluginName()
  1485.         {
  1486.             return "Insane Balancer";
  1487.         }
  1488.  
  1489.         public string GetPluginVersion()
  1490.         {
  1491.             return "0.0.0.5";
  1492.         }
  1493.  
  1494.         public string GetPluginAuthor()
  1495.         {
  1496.             return "micovery";
  1497.         }
  1498.  
  1499.         public string GetPluginWebsite()
  1500.         {
  1501.             return "www.insanegamersasylum.com";
  1502.         }
  1503.  
  1504.  
  1505.         public string GetPluginDescription()
  1506.         {
  1507.             return @"
  1508.        <h2>Description</h2>
  1509.        <p> This is the draft impelementation for a flexible team balancer, which can balance teams by skill, rank, score, kdr and other rules.
  1510.            All of it, while doing best effort to maintain squads together, and clans on the same team.
  1511.        </p>
  1512.  
  1513.        <h2>Sort Methods</h2>
  1514.        <p> A sort method is a rule used for sorting a list of players or squads. The following balancing methods are supported:
  1515.        </p>
  1516.        <ul>
  1517.            
  1518.            <li><b>kpm_asc_round</b> , <b>kpm_desc_round</b> <br />
  1519.             Sorting based on the soldier round kills per minute
  1520.            </li>
  1521.            <li><b>spm_asc_round</b> , <b>spm_desc_round</b> <br />
  1522.             Sorting based on the soldier round score per minute
  1523.            </li>
  1524.            <li><b>kdr_asc_round</b> , <b>kdr_desc_round</b> <br />
  1525.             Sorting based on the soldier round kill to death ratio  
  1526.            </li>
  1527.          
  1528.            <li><b>score_asc_round</b> , <b>score_desc_round</b> <br />
  1529.             Sorting based on the soldier round score  
  1530.            </li>
  1531.            <li><b>time_asc_round</b> , <b>time_desc_round</b> <br />
  1532.             Sorting based on the time the player joined the server.
  1533.            </li>
  1534.  
  1535.        </ul>
  1536.  
  1537.            All the data for sorting rules ending in <b>_round</b> is obtained from the previous or current round statistics.
  1538.      
  1539.        <h2>Live Balancing Logic</h2>
  1540.                          
  1541.        <blockquote>
  1542.        Insane Balancer tries to be as un-intrusive as posible while balancing a game that is in progress.
  1543.        If the teams become un-balanced while the game is in progess it will create two pools of players and sort them.
  1544.        (players chosen from the bigger team) One pool for players who are not in any squad, and another pool for squads.
  1545.        First it will chose the player at the top of the no-squad pool and move it to the other team until teams are balanced.
  1546.        If the no-squad pool becomes empty (and teams are still unbalanced) then squad at the top of the squad pool is moved
  1547.        to the other team if the number of players needed is greater than or equal to the size of the squad. If the number of players
  1548.        needed is less than the size of the top squad, a random random player is chosen from the squad and moved to the opposite team
  1549.        until teams are balanced. (players that were on the same squad are kept together)
  1550.        </blockquote>
  1551.  
  1552.        
  1553.        <h2>Round Re-balancing Logic</h2>
  1554.                          
  1555.        <blockquote>
  1556.        If end of round balancing is enabled, Insane Balancer will completely re-sort teams, even if they are already balanced.
  1557.        The logic for the re-sort is as follows. Create two pools of players and sort them (choosing players from all teams).
  1558.        One pool for players who are not in squads, and another for players who are in squads. Then, move all all players and squads
  1559.        to the neutral team, in order to end up with two empty non-neutral teams. Then, pick the squad at the top of the squad pool,
  1560.        and move it to the losing team. Then pick the next squad on top of the squad pool, and move it to the team with the least players, and so on.
  1561.        Once the squad pool is empty, pick the player on top of the no-squad pool, and move it to the team with least players, and so on.
  1562.        If teams are still unbalanced after the no-squad pool is empty, then the live balancing logic is applied.<br />
  1563.        <br />
  1564.        This is a high-level explanation explanation of the round-balancing logic algorithm. It does not mean that players are actually moved to
  1565.        the neutral team. This is not possible anymore with Battlefield 3. Instead, it's done virtually with 3 arrays of players to represent
  1566.        the three teams: Neutral, US, and RU. When all the calculations are done, and the plugin has determined the target teams and squad for each
  1567.        player ... it will then swap players between RU, and US one at a time.<br />
  1568.        <br />
  1569.        Note that if the server is full, round-balacing logic will not be applied. It's not possible to move players when both teams are full.
  1570.        Also note that, it can happen that the server becomes full while the round-balancing is being applied. When this happens, the admin.movePlayer
  1571.        commands may fail. This was not a problem in Battlefield Bad Company 2, because there was a spare/neutral team that players could be moved to
  1572.        when balancing a full server.
  1573.      
  1574.        </blockquote>
  1575.  
  1576.        
  1577.        <h2>Balanced Team Determination </h2>
  1578.        
  1579.        <blockquote>
  1580.        Teams are determined to be balanced if the difference in number of players between teams is less than or equal to the <b>balance_threshold</b>.
  1581.        The <b>balance_threshold</b> has to be a number greater than 0. If the total number of players in the server is less than or equal to the
  1582.        <b>balance_threshold</b>, then the user set threshold is ignored, and a value of 1 is used instead. Technically, no team should ever be bigger
  1583.        than the other by more than the value of <b>balance_threshold</b>.
  1584.        </blockquote>
  1585.  
  1586.        <h2>Keeping Squads Together </h2>
  1587.  
  1588.        <blockquote>
  1589.        Insane Balancer is coded to keep squads together by default. However, you can set <b>keep_squads</b> to false and both round-balancing and
  1590.        live-balancing logics are changed a bit. What happens, is that all squads in the squad pool are broken, and players put into the no-squad pool,
  1591.        before balancing starts.<br />
  1592.        <br />
  1593.        Note that for live-balancing, players are not actually moved out of the squad. (it would kill all players if you do that).
  1594.        They are just treated as if they were not in a squad. Also, If <b>keep_squads</b> is enabled, clan-squads will not be broken.
  1595.        </blockquote>
  1596.  
  1597.        <h2> Keeping Clans On Same Team (requires Battlelog credentials) </h2>  
  1598.  
  1599.        <blockquote>                                                                        
  1600.        During end-of round re-balancing, if <b>keep_clans</b> is enabled, players with the same clan tag are be removed from their current squad,
  1601.        and put into exclusive squads. These special clan squads are given priority over non-clan squads, so that clan-squads end up in the same team.
  1602.        Note that when <b>keep_clans</b> is enabled, teams may end up unbalanced in number, so the live-balancing logic may still need to be applied.<br />
  1603.        <br />
  1604.        During live-balancing, if <b>keep_clans</b> is enabled, players with clan tags are given priority, as long as there is at least two members of
  1605.        the same clan in the server. When picking players to move to the other team, if a player has a clan tag, the player will be automatically skipped,
  1606.        if the majority of the clan is in the same team (otherwise the player is moved to the other team to join his clan buddies).
  1607.        If at the end of live-balancing phase, teams are still unbalanced, then <b>keep_clans</b> is disabled temporarily, and the live-balancer logic is applied again.
  1608.        </blockquote>        
  1609.  
  1610.        <h2>Settings</h2>
  1611.        <ol>
  1612.          <li><blockquote><b>balance_threshold</b><br />
  1613.                <i>(integer > 0)</i> -  maximum difference in team sizes before teams are considered unbalanced <br />
  1614.                Technically, no team will ever be bigger by more than the <b>balance_threshold</b>
  1615.                </blockquote>
  1616.          </li>
  1617.          <li><blockquote><b>live_interval_time</b><br />
  1618.                <i>(integer > 0)</i> - interval number of seconds at which team balance is checked during game  <br />
  1619.                </blockquote>
  1620.          </li>
  1621.          <li><blockquote><b>round_interval</b><br />
  1622.                <i>(integer > 0)</i> - interval number number of rounds at which the round balancer is applied  <br />
  1623.                For example, if map Atacama has 6 rounds, and the value of <b>round_interval</b> is 2, then the round
  1624.                balancer is run at the end of rounds 2, 4, and 6. <br />
  1625.                <br />
  1626.                This value is used for all maps, unless you provide a per-map interval value. <br />
  1627.                Per-map round interval values can be set in the ""Round Interval"" section of the plugin.<br />
  1628.                There you will see a list of maps, and game modes supported by BF3. <br />
  1629.  
  1630.                <br />
  1631.                The following prefixes are used to identify game modes:<br />
  1632.                <ul>
  1633.                   <li><i>cl</i> - conquest large </li>
  1634.                   <li><i>cs</i> - conquest small </li>
  1635.                   <li><i>rl</i> - rush large </li>
  1636.                   <li><i>sr</i> - squad rush </li>
  1637.                   <li><i>td</i> - team death-match </li>
  1638.                </ul>
  1639.                </blockquote>
  1640.          </li>
  1641.          <li><blockquote><b>round_wait_time</b><br />
  1642.                <i>(integer > 0)</i> - number of seconds to wait after round-over event, before activating the round-end balancer <br />
  1643.                </blockquote>
  1644.          </li>
  1645.          <li><blockquote><strong>keep_squads_live</strong><br />
  1646.                <i>true</i> - squads are preseved during live balancing <br />
  1647.                <i>false</i> - squads are intentionally broken up during live balancing
  1648.                </blockquote>
  1649.                This setting only applies to the round-end balancer.
  1650.          </li>
  1651.          <li><blockquote><strong>keep_squads_round</strong><br />
  1652.                <i>true</i> - squads are preseved during end of round balancing <br />
  1653.                <i>false</i> - squads are intentionally broken up during end of round balancing
  1654.                </blockquote>
  1655.                This setting only applies to the round-end balancer.
  1656.          </li>
  1657.          <li><blockquote><strong>keep_clans_round</strong><br />
  1658.                <i>true</i> - players with same clan tags are kept on the same team during end of round balancing <br />
  1659.                <i>false</i> - clan tags are ignored during end of round balancing
  1660.                </blockquote>
  1661.          </li>
  1662.          <li><blockquote><strong>keep_clans_live</strong><br />
  1663.                <i>true</i> - players with same clan tags are kept on the same team during live balancing <br />
  1664.                <i>false</i> - clan tags are ignored during live balancing
  1665.                </blockquote>
  1666.          </li>
  1667.          <li><blockquote><strong>warn_say</strong><br />
  1668.                <i>true</i> - send auto-balancer warning in chat <br />
  1669.                <i>false</i> - do not say the auto-balancer warning in chat
  1670.                </blockquote>
  1671.          </li>
  1672.          <li><blockquote><strong>balance_round</strong><br />
  1673.                <i>true</i> - enables the end of round balancer<br />
  1674.                <i>false</i> - disabled the end of round balancer
  1675.                </blockquote>
  1676.          </li>
  1677.          <li><blockquote><strong>balance_live</strong><br />
  1678.                <i>true</i> - enables the live balancer<br />
  1679.                <i>false</i> - disables the live balancer
  1680.                </blockquote>
  1681.          </li>
  1682.          <li><blockquote><strong>admin_list</strong><br />
  1683.                <i>(string)</i> - list of players who are allow to execute admin commands      
  1684.                </blockquote>
  1685.           </li>        
  1686.           <li><blockquote><strong>round_sort</strong><br />
  1687.                <i>(string)</i> - method used for sorting players and squads during end of round balancing      
  1688.                </blockquote>
  1689.           </li>
  1690.           <li><blockquote><strong>live_sort</strong><br />
  1691.                <i>(string)</i> - method used for sorting players and squads during live balancing      
  1692.                </blockquote>
  1693.           </li>
  1694.           <li><blockquote><strong>console</strong><br />
  1695.                <i>(string)</i> - here you can use to test the in-game commands from within procon. </br>
  1696.                For example: ""!show round stats"" will print the player statistic for the current round in the plugin console.    
  1697.                </blockquote>
  1698.           </li>
  1699.        </ol>
  1700.  
  1701.        <h2>Public In-Game Commands</h2>
  1702.        <p>
  1703.            In-game commands are messages typed into the game chat box, which have special meaning to the plugin.
  1704.            Commands must start with one of the following characters: !,@, or /. This plugin interprets the following commands:
  1705.        </p>
  1706.        <ul>
  1707.           <li><blockquote><strong>!move</strong><br />
  1708.               This command can be used by regular players to move themselves to the opposite team as long as teams are balanced.
  1709.               </blockquote>
  1710.           </li>
  1711.        </ul>
  1712.       <h2> Admin In-Game Commands</h2>
  1713.        <p>
  1714.            These are the commands that only soldiers in the ""admin_list"" are allowed to execute. Reply messages generated by admin commands
  1715.            are sent only to the admin who executed the command.
  1716.        </p>
  1717.        <ul>
  1718.           <li><blockquote><strong>!start check</strong><br />
  1719.               This command puts the live balancer in started state, so that it periodically (every <b>live_interval_time</b> seconds) checks the teams for balance. <br />
  1720.               When this command is run <b>balance_live</b>is implicitly set to true.
  1721.               </blockquote>
  1722.           </li>
  1723.           <li><blockquote><strong>!stop check</strong><br />
  1724.                This command puts the live balancer in stopped state.
  1725.                When this command is run <b>balance_live</b> is implicitly set to false.
  1726.               </blockquote>
  1727.           </li>
  1728.           <li><blockquote><strong>!show round stats [player-name]</strong><br />
  1729.                This command is used for showing the player statistics for the current round.
  1730.                The name of the player is optional. If you do not provide a player name, it will print statistics for all players.
  1731.               </blockquote>
  1732.           </li>
  1733.           <li><blockquote><strong>!balance live</strong><br />
  1734.               This command forces the live balancing logic to be applied whithout any warning period or countdown.
  1735.               </blockquote>
  1736.           </li>
  1737.          <li><blockquote><strong>!balance round</strong><br />
  1738.               This command forces the round balancing logic to be applied whithout any warning period or countdown.
  1739.               </blockquote>
  1740.           </li>
  1741.           <li><blockquote>
  1742.                <strong>1. !set {variable} {to|=} {value}</strong><br />
  1743.                <strong>2. !set {variable} {value}</strong><br />      
  1744.                <strong>3. !set {variable}</strong><br />  
  1745.                This command is used for setting the value of this plugin's variables.<br />
  1746.                For the 2nd invocation syntax you cannot use ""="" or ""to"" as the variable value. <br />
  1747.                For the 3rd invocation syntax the value is assumed to be ""true"".
  1748.               </blockquote>
  1749.           </li>
  1750.           <li><blockquote>
  1751.                <strong>!get {variable} </strong><br />
  1752.                This command prints the value of the specified variable.
  1753.               </blockquote>
  1754.           </li>
  1755.         </ul>
  1756.        ";
  1757.         }
  1758.  
  1759.         public void OnPluginLoaded(string strHostName, string strPort, string strPRoConVersion)
  1760.         {
  1761.             ConsoleWrite("plugin loaded");
  1762.             this.RegisterEvents("OnPlayerJoin",
  1763.                                 "OnPlayerKilled",
  1764.                                 "OnPlayerSpawned",
  1765.                                 "OnPlayerLeft",
  1766.                                 "OnGlobalChat",
  1767.                                 "OnTeamChat",
  1768.                                 "OnSquadChat",
  1769.                                 "OnLevelStarted",
  1770.                                 "OnPunkbusterplayerStatsCmd",
  1771.                                 "OnServerInfo",
  1772.                                 "OnPlayerTeamChange",
  1773.                                 "OnPlayerMovedByAdmin",
  1774.                                 "OnPlayerKickedByAdmin",
  1775.                                 "OnPlayerSquadChange",
  1776.                                 "OnplayersStatsCmd",
  1777.                                 "OnRoundOver");
  1778.         }
  1779.  
  1780.         public void OnPluginEnable()
  1781.         {
  1782.  
  1783.  
  1784.             ConsoleWrite("^b^2Enabled!^0");
  1785.  
  1786.             plugin_enabled = true;
  1787.  
  1788.             unloadSettings();
  1789.             loadSettings();
  1790.  
  1791.  
  1792.             addPluginCallTask("InsaneBalancer", "ticks", 0, 1, -1);
  1793.             initializeBalancer();
  1794.         }
  1795.  
  1796.         public String[] getMailPass()
  1797.         {
  1798.             String mail = getStringVarValue("mail");
  1799.             String pass = getStringVarValue("pass");
  1800.             if (Regex.Match(mail, @"^\s*$").Success || Regex.Match(pass, @"^\s*$").Success)
  1801.                 return null;
  1802.  
  1803.             return new String[] { mail, pass };
  1804.         }
  1805.  
  1806.  
  1807.         public void addPluginCallTask(string task, string method, int delay, int interval, int repeat)
  1808.         {
  1809.             this.ExecuteCommand("procon.protected.tasks.add", task, delay.ToString(), interval.ToString(), repeat.ToString(), "procon.protected.plugins.call", "InsaneBalancer", method);
  1810.         }
  1811.  
  1812.         public void removeTask(string task)
  1813.         {
  1814.             this.ExecuteCommand("procon.protected.tasks.remove", task);
  1815.         }
  1816.  
  1817.         public int getElapsedTime(DateTime now, PluginState state)
  1818.         {
  1819.             DateTime startTime = getStartTime(state);
  1820.             int elapsed = (int)now.Subtract(startTime).TotalSeconds;
  1821.             return elapsed;
  1822.         }
  1823.  
  1824.         public DateTime getStartTime(PluginState state)
  1825.         {
  1826.             if (state.Equals(PluginState.wait))
  1827.                 return startWaitTime;
  1828.             else if (state.Equals(PluginState.warn))
  1829.                 return startWarnTime;
  1830.             else if (state.Equals(PluginState.check))
  1831.                 return startCheckTime;
  1832.             else if (state.Equals(PluginState.balance))
  1833.                 return startBalanceTime;
  1834.             else if (state.Equals(PluginState.stop))
  1835.                 return startStopTime;
  1836.             else
  1837.                 ConsoleWrite("^1^bWARNING^0^n: cannot find start time for ^b" + state.ToString() + "^n^0");
  1838.  
  1839.             return utc;
  1840.         }
  1841.  
  1842.         public void setStartTime(PluginState state, DateTime now)
  1843.         {
  1844.             if (state.Equals(PluginState.wait))
  1845.                 startWaitTime = now;
  1846.             else if (state.Equals(PluginState.warn))
  1847.                 startWarnTime = now;
  1848.             else if (state.Equals(PluginState.check))
  1849.                 startCheckTime = now;
  1850.             else if (state.Equals(PluginState.balance))
  1851.                 startBalanceTime = now;
  1852.             else if (state.Equals(PluginState.stop))
  1853.                 startStopTime = now;
  1854.             else
  1855.                 ConsoleWrite("^1^bWARNING^0^n: cannot set start time for ^b" + state.ToString() + "^n^0");
  1856.         }
  1857.  
  1858.  
  1859.         public int getMaxTime(PluginState state)
  1860.         {
  1861.             if (state.Equals(PluginState.wait))
  1862.                 return getIntegerVarValue("live_interval_time");
  1863.             else if (state.Equals(PluginState.warn))
  1864.                 return getIntegerVarValue("warn_msg_total_time");
  1865.             /*else
  1866.                 DebugWrite("^1Getting max time for ^b" + state.ToString() + "^n state is not valid", 6);
  1867.             */
  1868.  
  1869.             return getElapsedTime(utc, PluginState.check);
  1870.         }
  1871.  
  1872.         public int getRemainingTime(DateTime now, PluginState state)
  1873.         {
  1874.  
  1875.             int max_time = getMaxTime(state);
  1876.             int elapsed = getElapsedTime(now, state);
  1877.  
  1878.             int remain = max_time - elapsed;
  1879.             return remain;
  1880.         }
  1881.  
  1882.  
  1883.         public void ExecCommand(params string[] args)
  1884.         {
  1885.             List<string> list = new List<string>();
  1886.             list.Add("procon.protected.send");
  1887.             list.AddRange(args);
  1888.             this.ExecuteCommand(list.ToArray());
  1889.         }
  1890.  
  1891.  
  1892.  
  1893.         public void getPlayerList()
  1894.         {
  1895.             ExecCommand("admin.listPlayers", "all");
  1896.             ExecCommand("punkBuster.pb_sv_command", "pb_sv_plist");
  1897.         }
  1898.  
  1899.         public void getServerInfo()
  1900.         {
  1901.             ExecCommand("serverInfo");
  1902.         }
  1903.  
  1904.  
  1905.         public void ticks()
  1906.         {
  1907.             utc = utc.AddSeconds(1);
  1908.             timer(utc);
  1909.  
  1910.         }
  1911.  
  1912.         public bool isPluginState(PluginState state)
  1913.         {
  1914.             return pluginState.Equals(state);
  1915.         }
  1916.  
  1917.         public bool isPluginWaiting()
  1918.         {
  1919.             return isPluginState(PluginState.wait);
  1920.         }
  1921.  
  1922.         public bool isPluginBalancing()
  1923.         {
  1924.             return isPluginState(PluginState.balance);
  1925.         }
  1926.  
  1927.         public bool isPluginWarning()
  1928.         {
  1929.             return isPluginState(PluginState.warn);
  1930.         }
  1931.  
  1932.         public bool isPluginStopped()
  1933.         {
  1934.             return isPluginState(PluginState.stop);
  1935.         }
  1936.  
  1937.         public bool isPluginChecking()
  1938.         {
  1939.             return isPluginState(PluginState.check);
  1940.         }
  1941.  
  1942.         public void startCheckState(DateTime now)
  1943.         {
  1944.  
  1945.             if (check_state_phase == 0)
  1946.             {
  1947.                 pluginState = PluginState.check;
  1948.                 setStartTime(pluginState, now.AddSeconds(1));
  1949.                 DebugWrite("^b" + pluginState + "^n state started " + getStartTime(pluginState).ToString() + "^n^0", 1);
  1950.  
  1951.                 DebugWrite("^b" + PluginState.check.ToString() + "^n state ^bphase-" + check_state_phase + "^n started " + getStartTime(pluginState).ToString() + "^0", 2);
  1952.                 DebugWrite("Requesting player list", 2);
  1953.  
  1954.                 check_state_phase = 1;
  1955.                 getPlayerList();
  1956.  
  1957.  
  1958.                 return;
  1959.             }
  1960.             else if (check_state_phase == 1)
  1961.             {
  1962.  
  1963.                 DebugWrite("^b" + PluginState.check.ToString() + "^n state ^bphase-" + check_state_phase + "^n started " + now.ToString() + "^0", 2);
  1964.  
  1965.  
  1966.  
  1967.                 if (teamsUnbalanced())
  1968.                 {
  1969.                     DebugWrite("Teams are unbalanced, going to ^b" + PluginState.warn.ToString() + "^n state", 2);
  1970.                     startWarnState(now);
  1971.                 }
  1972.                 else
  1973.                 {
  1974.                     DebugWrite("Teams are balanced, going to ^b" + PluginState.wait.ToString() + "^n state", 2);
  1975.                     restartWaitState(now);
  1976.                 }
  1977.  
  1978.                 check_state_phase = 0;
  1979.  
  1980.                 return;
  1981.             }
  1982.         }
  1983.  
  1984.         public void timer(DateTime now)
  1985.         {
  1986.  
  1987.             if (!getBooleanVarValue("balance_live"))
  1988.                 return;
  1989.  
  1990.             int remain_time = getRemainingTime(now, pluginState);
  1991.             int elapsed_time = getElapsedTime(now, pluginState);
  1992.  
  1993.  
  1994.             if (isPluginChecking() || isPluginStopped() || isPluginBalancing())
  1995.                 DebugWrite(pluginState.ToString() + "(" + elapsed_time + ")", 4);
  1996.             else
  1997.                 DebugWrite(pluginState.ToString() + "(" + remain_time + ")", 4);
  1998.  
  1999.  
  2000.  
  2001.             if (isPluginStopped())
  2002.             {
  2003.                 if (getBooleanVarValue("auto_start"))
  2004.                 {
  2005.                     DebugWrite("^bauto_start^n is enabled, going to ^b" + PluginState.wait.ToString() + "^n state^0", 2);
  2006.                     startWaitSate(now);
  2007.                 }
  2008.             }
  2009.             else if (isPluginWaiting())
  2010.             {
  2011.                 if (remain_time <= 0)
  2012.                     startCheckState(now);
  2013.             }
  2014.             else if (isPluginWarning())
  2015.             {
  2016.                 int countdown_time = getIntegerVarValue("warn_msg_countdown_time");
  2017.                 int display_time = getIntegerVarValue("warn_msg_display_time");
  2018.                 int interval_time = getIntegerVarValue("warn_msg_interval_time");
  2019.  
  2020.                 if (teamsBalanced())
  2021.                 {
  2022.                     DebugWrite("Teams are balanced, halting ^b" + PluginState.warn.ToString() + "^n state, and restarting ^b" + PluginState.wait.ToString() + "^n state^0", 4);
  2023.                     restartWaitState(now);
  2024.                     return;
  2025.                 }
  2026.                 else if (remain_time <= 0)
  2027.                 {
  2028.                     balanceLive(now);
  2029.                     restartWaitState(now);
  2030.                     return;
  2031.                 }
  2032.                 else if (remain_time >= 1 && remain_time <= countdown_time)
  2033.                 {
  2034.                     warnCountdown();
  2035.                     return;
  2036.                 }
  2037.                 else if (isTimeLeft(remain_time, display_time, interval_time, countdown_time))
  2038.                 {
  2039.                     warnAnnounce(display_time);
  2040.                     return;
  2041.                 }
  2042.             }
  2043.         }
  2044.  
  2045.  
  2046.         private bool teamsUnbalanced()
  2047.         {
  2048.             return !teamsBalanced();
  2049.         }
  2050.  
  2051.         private bool teamsBalanced()
  2052.         {
  2053.  
  2054.             //return false;
  2055.             /* initialize hash with player count for 16 teams*/
  2056.             Dictionary<int, int> player_count = getPlayerCount();
  2057.             int total = player_count[1] + player_count[2];
  2058.  
  2059.             int difference = Math.Abs(player_count[1] - player_count[2]);
  2060.             int balance_threshold = getIntegerVarValue("balance_threshold");
  2061.  
  2062.             /* assumer the minimum threshold if user total players is less than user set threshold */
  2063.             int threshold = (total <= balance_threshold) ? 1 : balance_threshold;
  2064.  
  2065.  
  2066.  
  2067.             if (difference <= balance_threshold)
  2068.                 return true;
  2069.  
  2070.             return false;
  2071.         }
  2072.  
  2073.         private int sumSquadPlayers(List<PlayerSquad> squads)
  2074.         {
  2075.             int sum = 0;
  2076.             foreach (PlayerSquad squad in squads)
  2077.                 sum += squad.getCount();
  2078.             return sum;
  2079.         }
  2080.  
  2081.         private void listPlayers()
  2082.         {
  2083.             DebugWrite("== Listing Players == ", 3);
  2084.             listPlayers(getPlayersProfile(""));
  2085.  
  2086.         }
  2087.  
  2088.         private void listPlayers(List<PlayerProfile> players_list)
  2089.         {
  2090.             int count = 1;
  2091.             foreach (PlayerProfile player in players_list)
  2092.             {
  2093.                 DebugWrite("    " + count + ". ^b" + player + "^n STeam(" + TN(player.getSavedTeamId()) + ").SSquad(" + SQN(player.getSavedSquadId()) + ") ... Team(" + TN(player.getTeamId()) + ").Squad(" + SQN(player.getSquadId()) + ")", 3);
  2094.                 count++;
  2095.             }
  2096.         }
  2097.  
  2098.  
  2099.         private List<PlayerSquad> getSquadsNotInWhiteList(List<PlayerSquad> squads)
  2100.         {
  2101.             return getSquadsByWhiteList(squads, false);
  2102.         }
  2103.  
  2104.         private List<PlayerSquad> getSquadsInWhiteList(List<PlayerSquad> squads)
  2105.         {
  2106.             return getSquadsByWhiteList(squads, true);
  2107.         }
  2108.  
  2109.         private List<PlayerSquad> getSquadsByWhiteList(List<PlayerSquad> squads, bool flag)
  2110.         {
  2111.             List<PlayerSquad> list = new List<PlayerSquad>();
  2112.  
  2113.             foreach (PlayerSquad squad in squads)
  2114.             {
  2115.                 bool in_whitelist = false;
  2116.                 foreach (PlayerProfile player in squad.getMembers())
  2117.                     if (isInMoveWhiteList(player))
  2118.                     {
  2119.                         in_whitelist = true;
  2120.                         break;
  2121.                     }
  2122.  
  2123.                 if (flag && in_whitelist)
  2124.                     list.Add(squad);
  2125.                 else if (!flag && !in_whitelist)
  2126.                     list.Add(squad);
  2127.  
  2128.             }
  2129.  
  2130.             return list;
  2131.         }
  2132.  
  2133.         private int mergePlayerWithTeam(PlayerProfile pp, int toTeamId)
  2134.         {
  2135.  
  2136.             if (pp.getTeamId() == toTeamId)
  2137.                 return 0;
  2138.  
  2139.             int players_moved = 0;
  2140.             int squad_max_sz = 4;
  2141.             int nosquadId = 0;
  2142.  
  2143.             List<PlayerSquad> squads = getAllSquads(toTeamId);
  2144.  
  2145.             /* sort the squads in increasing order of player count */
  2146.             squads.Sort(new Comparison<PlayerSquad>(squad_count_asc_cmp));
  2147.  
  2148.             DebugWrite("First looking for empty slots in squads for " + pp + " in Team(" + TN(toTeamId) + ")", 3);
  2149.             for (int i = 0; i < squads.Count; i++)
  2150.             {
  2151.                 PlayerSquad sorted_squad = squads[i];
  2152.  
  2153.                 if (sorted_squad.getCount() == squad_max_sz)
  2154.                     continue;
  2155.  
  2156.                 if (movePlayer(pp, sorted_squad.getTeamId(), sorted_squad.getSquadId()))
  2157.                 {
  2158.                     DebugWrite(pp + " moved to Team(" + TN(sorted_squad.getTeamId()) + ").Squad(" + SQN(sorted_squad.getTeamId()) + ")", 3);
  2159.                     sorted_squad.addPlayer(pp);
  2160.                     players_moved++;
  2161.                     break;
  2162.                 }
  2163.             }
  2164.  
  2165.             if (players_moved > 0)
  2166.                 return players_moved;
  2167.  
  2168.             DebugWrite("Could not find empty slots in squads for " + pp + " in Team(" + TN(toTeamId) + ")", 3);
  2169.             if (movePlayer(pp, toTeamId, nosquadId))
  2170.             {
  2171.                 DebugWrite(pp + " moved to Team(" + TN(toTeamId) + ").Squad(" + SQN(nosquadId) + ")", 3);
  2172.                 players_moved++;
  2173.             }
  2174.  
  2175.             return players_moved;
  2176.         }
  2177.  
  2178.         private int mergeSquadWithPool(PlayerSquad squad, List<PlayerSquad> squads)
  2179.         {
  2180.  
  2181.             int players_moved = 0;
  2182.             if (squad == null)
  2183.                 return 0;
  2184.  
  2185.             int squad_max_sz = 4;
  2186.  
  2187.             List<PlayerProfile> squad_players = squad.getMembers();
  2188.  
  2189.  
  2190.             /* sort the squads in increasing order of player count */
  2191.  
  2192.             squads.Sort(new Comparison<PlayerSquad>(squad_count_asc_cmp));
  2193.  
  2194.             for (int i = 0; i < squads.Count; i++)
  2195.             {
  2196.                 PlayerSquad sorted_squad = squads[i];
  2197.                 if (squad.getTeamId() == sorted_squad.getTeamId() &&
  2198.                     squad.getSquadId() == sorted_squad.getSquadId())
  2199.                     continue;
  2200.  
  2201.                 while (sorted_squad.getFreeSlots() > 0 && squad_players.Count > 0)
  2202.                 {
  2203.                     PlayerProfile squad_player = squad_players[0];
  2204.                     squad_players.RemoveAt(0);
  2205.                     if (movePlayer(squad_player, sorted_squad.getTeamId(), sorted_squad.getSquadId()))
  2206.                     {
  2207.                         DebugWrite(squad_player + " moved to Team(" + TN(squad_player.getTeamId()) + ").Squad(" + SQN(squad_player.getSquadId()) + ")", 3);
  2208.                         sorted_squad.addPlayer(squad_player);
  2209.                         players_moved++;
  2210.                     }
  2211.                 }
  2212.             }
  2213.  
  2214.             return players_moved;
  2215.         }
  2216.  
  2217.         private int kickOnePlayer(List<PlayerProfile> list)
  2218.         {
  2219.             foreach (PlayerProfile pp in list)
  2220.             {
  2221.                 if (isInKickWhiteList(pp))
  2222.                 {
  2223.                     DebugWrite("Player " + pp + " is idle, but cannot kick because he in white-list", 3);
  2224.                     continue;
  2225.                 }
  2226.                 ConsoleWrite("Kicking idle player ^bTeam(" + TN(pp.getTeamId()) + ").Squad(" + SQN(pp.getSquadId()) + ") " + pp + " from server");
  2227.                 KickPlayerWithMessage(pp, "kicked for inactivity when server was full");
  2228.                 return 1;
  2229.             }
  2230.  
  2231.             return 0;
  2232.         }
  2233.  
  2234.  
  2235.  
  2236.         private Dictionary<int, List<PlayerProfile>> getllAllIdle()
  2237.         {
  2238.             List<PlayerProfile> all = getPlayersProfile("");
  2239.  
  2240.             Dictionary<int, List<PlayerProfile>> idle = new Dictionary<int, List<PlayerProfile>>();
  2241.  
  2242.             foreach (PlayerProfile pp in all)
  2243.             {
  2244.                 if (!idle.ContainsKey(pp.getTeamId()))
  2245.                     idle.Add(pp.getTargetTeamId(), new List<PlayerProfile>());
  2246.  
  2247.                 if (!isPlayerIdle(pp))
  2248.                     continue;
  2249.  
  2250.                 idle[pp.getTargetTeamId()].Add(pp);
  2251.             }
  2252.  
  2253.             return idle;
  2254.  
  2255.         }
  2256.  
  2257.         private void balanceRound(int winTeamId)
  2258.         {
  2259.             if (!getBooleanVarValue("balance_round"))
  2260.             {
  2261.                 ConsoleWrite("Round balancer disbaled, not running");
  2262.                 return;
  2263.             }
  2264.  
  2265.             int loseTeamId = getOpposingTeamId(winTeamId);
  2266.             int neutralTeamId = 0;
  2267.             int team_sz = serverInfo.MaxPlayerCount / 2;
  2268.  
  2269.             /* find where the free slot is */
  2270.             Dictionary<int, int> pcounts = getPlayerCount();
  2271.             int total = pcounts[winTeamId] + pcounts[loseTeamId];
  2272.  
  2273.  
  2274.             if (total > serverInfo.MaxPlayerCount)
  2275.             {
  2276.                 ConsoleWrite("^1^bWARNING^n^0: detected that there are ^b" + total + "^n players, but DICE says the server size is ^b" + serverInfo.MaxPlayerCount + "^n ");
  2277.                 ConsoleWrite("^1^bWARNING^n^0: This makes no sense, DICE be trolling you! ");
  2278.                 ConsoleWrite("The highest player count I saw this round was ^b" + max_player_count + "^n, I will use that as server size instead (cross fingers)");
  2279.                 team_sz = max_player_count / 2;
  2280.             }
  2281.  
  2282.  
  2283.             Dictionary<int, int> fslots = new Dictionary<int, int>();
  2284.             fslots.Add(neutralTeamId, 0);
  2285.             fslots.Add(winTeamId, team_sz - pcounts[winTeamId]);
  2286.             fslots.Add(loseTeamId, team_sz - pcounts[loseTeamId]);
  2287.  
  2288.             if (!(fslots[winTeamId] > 0 || fslots[loseTeamId] > 0))
  2289.             {
  2290.                 if (getBooleanVarValue("kick_idle"))
  2291.                 {
  2292.                     Dictionary<int, List<PlayerProfile>> idle = getllAllIdle();
  2293.                     DebugWrite("^bkick_idle^n is ^bon^n, will try to find idle players to kick on Team("+TN(winTeamId)+") or Team("+TN(loseTeamId)+")", 3);
  2294.              
  2295.  
  2296.                     if (idle[winTeamId].Count == 0 && idle[loseTeamId].Count == 0)
  2297.                     {
  2298.                         ConsoleWrite("^1^bWARNING^0^n: No free player slots in either team, and no idle players, not balancing");
  2299.                         return;
  2300.                     }
  2301.  
  2302.                     /* kick at least 1 from win team */
  2303.                     fslots[winTeamId] += kickOnePlayer(idle[winTeamId]);
  2304.  
  2305.                     /* kick at least 1 from lose team */
  2306.                     fslots[loseTeamId] += kickOnePlayer(idle[loseTeamId]);
  2307.  
  2308.                     if (!(fslots[winTeamId] > 0 || fslots[loseTeamId] > 0))
  2309.                     {
  2310.                        ConsoleWrite("^1^bWARNING^0^n: Cannot find at least one idle player that is not in white-list, not balancing");
  2311.                        return;
  2312.                     }
  2313.                 }
  2314.      
  2315.                 ConsoleWrite("^1^bWARNING^0^n: No free player slots in either team, not balancing");
  2316.                 return;
  2317.             }
  2318.  
  2319.             DebugWrite("Team(" + TN(winTeamId) + ") has " + fslots[winTeamId] + " free slots", 3);
  2320.             DebugWrite("Team(" + TN(loseTeamId) + ") has " + fslots[loseTeamId] + " free slots", 3);
  2321.  
  2322.  
  2323.             int max_squads = 16;
  2324.             int max_squad_size = 4;
  2325.             virtual_mode = true;
  2326.             DateTime now = utc;
  2327.             pluginState = PluginState.balance;
  2328.             setStartTime(pluginState, now.AddSeconds(1));
  2329.             DebugWrite("^b" + pluginState + "_clans^n state started " + getStartTime(pluginState).ToString() + "^n^0", 1);
  2330.  
  2331.  
  2332.  
  2333.  
  2334.  
  2335.             DebugWrite("Saving original teams state", 3);
  2336.             List<PlayerProfile> all = getPlayersProfile("");
  2337.             all.ForEach(delegate(PlayerProfile pp) { pp.saveTeamSquad(); });
  2338.             listPlayers();
  2339.  
  2340.  
  2341.  
  2342.             DebugWrite("Building no-squad pool from ^bTeam(" + TN(winTeamId) + ")^n and ^bTeam(" + TN(loseTeamId) + ")^n^0", 3);
  2343.             List<PlayerProfile> win_nosquad_pool = getNoSquadPlayers(winTeamId);
  2344.             List<PlayerProfile> lose_nosquad_pool = getNoSquadPlayers(loseTeamId);
  2345.             List<PlayerProfile> nosquad_pool = new List<PlayerProfile>();
  2346.             nosquad_pool.AddRange(win_nosquad_pool);
  2347.             nosquad_pool.AddRange(lose_nosquad_pool);
  2348.  
  2349.             DebugWrite("No-squad pool has ^b" + nosquad_pool.Count + "^n player/s^0", 2);
  2350.             DebugWrite("Building squad pool from ^bTeam(" + TN(winTeamId) + ")^n and ^bTeam(" + TN(loseTeamId) + ")^n^0", 3);
  2351.  
  2352.             List<PlayerSquad> win_squad_pool = getNonEmptySquads(winTeamId);
  2353.             List<PlayerSquad> lose_squad_pool = getNonEmptySquads(loseTeamId);
  2354.             List<PlayerSquad> squad_pool = new List<PlayerSquad>();
  2355.             squad_pool.AddRange(win_squad_pool);
  2356.             squad_pool.AddRange(lose_squad_pool);
  2357.  
  2358.  
  2359.  
  2360.             DebugWrite("Squad pool has ^b" + squad_pool.Count + "^n squads^0", 3);
  2361.             listSquads(squad_pool);
  2362.  
  2363.             if (!getBooleanVarValue("keep_squads_round"))
  2364.             {
  2365.                 foreach (PlayerSquad squad in squad_pool)
  2366.                 {
  2367.                     DebugWrite("Breaking up ^bTeam(" + TN(squad.getTeamId()) + ").Squad(" + SQN(squad.getSquadId()) + ")^n^0", 3);
  2368.                     while (squad.getCount() > 0)
  2369.                     {
  2370.                         PlayerProfile player = squad.removeRandomPlayer();
  2371.                         if (movePlayer(player, player.getTeamId(), 0, true))
  2372.                             nosquad_pool.Add(player); /* only add to no-squad list if move succeeded */
  2373.                     }
  2374.                 }
  2375.             }
  2376.  
  2377.             DebugWrite("Moving no-squad pool to neutral ^bTeam(" + TN(neutralTeamId) + ")^n^0", 3);/*HACK HACK HACK patch for whitelist support per microvery - hadlock 12/10/11*/
  2378.             List<PlayerProfile> nosquad_pool_remove = new List<PlayerProfile>();
  2379.             foreach (PlayerProfile player in nosquad_pool)
  2380.             {
  2381.                 if (!movePlayer(player, neutralTeamId, 0, true))
  2382.                     nosquad_pool_remove.Add(player); /*  move failed, remove him from no squad pool (probably in whitelist) */
  2383.                  
  2384.             }
  2385.  
  2386.             /* drop the players that were marked for removing */
  2387.             foreach (PlayerProfile pp in nosquad_pool_remove)
  2388.                 nosquad_pool_remove.Remove(pp);
  2389.  
  2390.  
  2391.             DebugWrite("Moving squad pool to neutral ^bTeam(" + TN(neutralTeamId) + ")^n^0", 3);
  2392.             foreach (PlayerSquad squad in squad_pool)
  2393.                 moveSquad(squad, neutralTeamId, team_sz * 2);
  2394.  
  2395.  
  2396.             /* re-build the pools */
  2397.             DebugWrite("", 3);
  2398.             DebugWrite("Rebuilding no-squad pool from ^bTeam(" + TN(winTeamId) + ")^n and ^bTeam(" + TN(loseTeamId) + ")^n^0", 3);
  2399.             nosquad_pool = getNoSquadPlayers(neutralTeamId);
  2400.             DebugWrite("No-squad pool has ^b" + nosquad_pool.Count + "^n player/s^0", 3);
  2401.  
  2402.  
  2403.             DebugWrite("", 3);
  2404.             DebugWrite("Rebuilding squad pool from ^bTeam(" + TN(winTeamId) + ")^n and ^bTeam(" + TN(loseTeamId) + ")^n^0", 3);
  2405.             squad_pool = getNonEmptySquads(neutralTeamId);
  2406.             DebugWrite("Squad pool has ^b" + squad_pool.Count + "^n squads^0", 2);
  2407.             listSquads(squad_pool);
  2408.  
  2409.  
  2410.             if (getBooleanVarValue("keep_clans_round"))
  2411.             {
  2412.                 DebugWrite("Keeping clans in same team", 3);
  2413.  
  2414.                 /* collect statistics about clans */
  2415.                 DebugWrite("Collecting clan statistics", 3);
  2416.                 Dictionary<string, int> clan_stats = new Dictionary<string, int>();
  2417.                 getClanStats(nosquad_pool, clan_stats);
  2418.                 foreach (PlayerSquad squad in squad_pool)
  2419.                     getClanStats(squad.getMembers(), clan_stats);
  2420.  
  2421.  
  2422.                 List<string> clanlist = new List<string>(clan_stats.Keys);
  2423.                 DebugWrite("^b" + clanlist.Count + "^n clans in server: [^b" + String.Join("^n], [^b", clanlist.ToArray()) + "^n]", 3);
  2424.  
  2425.  
  2426.                 int count = 1;
  2427.                 foreach (KeyValuePair<string, int> pair in clan_stats)
  2428.                 {
  2429.                     DebugWrite("    " + count + ". clan [^b" + pair.Key + "^n] has ^b" + pair.Value + "^n member/s", 3);
  2430.                     count++;
  2431.                 }
  2432.  
  2433.  
  2434.                 /* for clans with more than two players in game, create a new squad for them, and remove them from their current squads */
  2435.                 Dictionary<string, List<PlayerSquad>> clan_squads = new Dictionary<string, List<PlayerSquad>>();
  2436.                 DebugWrite("Creating clan squads from ^bno-squad^n pool", 3);
  2437.                 getClanSquads(nosquad_pool, clan_squads, clan_stats);
  2438.                 DebugWrite("Creating clan squads from ^bsquad-spool^n pool", 3);
  2439.                 foreach (PlayerSquad squad in squad_pool)
  2440.                     getClanSquads(squad.getMembers(), clan_squads, clan_stats);
  2441.  
  2442.                 /* remove the empty squads */
  2443.                 DebugWrite("Removing empty squads", 3);
  2444.                 squad_pool.RemoveAll(delegate(PlayerSquad squad) { return squad.getCount() == 0; });
  2445.                 DebugWrite("squad-pool has now " + squad_pool.Count, 3);
  2446.  
  2447.  
  2448.                 int new_squads_count = 0;
  2449.                 List<PlayerSquad> clan_squad_pool = new List<PlayerSquad>();
  2450.                 foreach (KeyValuePair<string, List<PlayerSquad>> pair in clan_squads)
  2451.                 {
  2452.                     List<PlayerSquad> csquads = pair.Value;
  2453.                     DebugWrite(csquads.Count + " squads for clan ^b[" + csquads[0].getMajorityClanTag() + "]^n", 3);
  2454.                     DebugWrite("----------------------------------------------------------", 3);
  2455.                     listSquads(csquads);
  2456.  
  2457.                     clan_squad_pool.AddRange(csquads);
  2458.                     new_squads_count += csquads.Count;
  2459.                 }
  2460.  
  2461.  
  2462.  
  2463.                 List<int> empty_squad_ids = new List<int>();
  2464.                 DebugWrite("Total of ^b" + new_squads_count + "^n new clan-squads created", 3);
  2465.                 if ((max_squads - squad_pool.Count) < new_squads_count)
  2466.                 {
  2467.                     int squads_to_remove_count = 0;
  2468.                     int squads_to_ignore_count = 0;
  2469.                     int fixed_new_count = 0;
  2470.  
  2471.                     int free_squad_slots = (max_squads - squad_pool.Count);
  2472.                     int extra = new_squads_count - free_squad_slots;
  2473.  
  2474.                     if (extra < squad_pool.Count)
  2475.                         squads_to_remove_count = extra;
  2476.                     else
  2477.                         squads_to_remove_count = squad_pool.Count;
  2478.  
  2479.  
  2480.                     squads_to_ignore_count = extra - squads_to_remove_count;
  2481.  
  2482.                     fixed_new_count = new_squads_count - squads_to_ignore_count;
  2483.  
  2484.                     if (squads_to_ignore_count > 0)
  2485.                         DebugWrite("Out of those new clan-squads,  ^b" + squads_to_ignore_count + "^n  will be ignored", 3);
  2486.  
  2487.                     DebugWrite("There are already " + squad_pool.Count + "^n non-clan squads in ^bTeam(" + TN(neutralTeamId) + ")^n", 3);
  2488.                     DebugWrite("Out of those non-clan squads, " + squads_to_remove_count + " will be removed to make room for " + fixed_new_count + " new clan-squads", 3);
  2489.  
  2490.  
  2491.                     List<PlayerSquad> squads_to_remove = new List<PlayerSquad>();
  2492.  
  2493.                     /* find squads to remove from the list of squads without players in white-list*/
  2494.                     List<PlayerSquad> no_whitelist_squads = getSquadsNotInWhiteList(squad_pool);
  2495.  
  2496.                     /* we may have not found enough squads to remove from the non-whitelist squads */
  2497.                     int extra_squads_needed = 0;
  2498.                     if (no_whitelist_squads.Count < squads_to_remove_count)
  2499.                     {
  2500.                         extra_squads_needed = squads_to_remove_count - no_whitelist_squads.Count;
  2501.                         squads_to_remove_count = no_whitelist_squads.Count;
  2502.                         DebugWrite("Only found ^b" + no_whitelist_squads.Count + " non-clan squads without players in white-list, ^b" + squads_to_remove_count + "^n are needed", 3);
  2503.                         DebugWrite("Will pick ^b" + extra_squads_needed + "^n extra squads from non-clan pool to remove regardless of white-list", 3);
  2504.                     }
  2505.  
  2506.                     squads_to_remove.AddRange(no_whitelist_squads.GetRange(0, squads_to_remove_count));
  2507.                     if (extra_squads_needed > 0)
  2508.                     {
  2509.                         List<PlayerSquad> whitelisted_squads = getSquadsInWhiteList(squad_pool);
  2510.                         squads_to_remove.AddRange(whitelisted_squads.GetRange(0, extra_squads_needed));
  2511.                     }
  2512.  
  2513.                     DebugWrite("The following squads will be removed removed from ^bTeam(" + TN(neutralTeamId) + ")", 3);
  2514.                     DebugWrite("----------------------------------------------------------------------", 3);
  2515.                     listSquads(squads_to_remove);
  2516.  
  2517.                     while (squads_to_remove.Count > 0)
  2518.                     {
  2519.                         PlayerSquad squad_to_remove = squads_to_remove[0];
  2520.                         squads_to_remove.RemoveAt(0);
  2521.                         empty_squad_ids.Add(squad_to_remove.getSquadId());
  2522.                         int squad_sz = squad_to_remove.getCount();
  2523.  
  2524.                         DebugWrite("Looking for empty slots in existing squads, for memebers of " + squad_to_remove, 3);
  2525.  
  2526.                         squad_sz -= mergeSquadWithPool(squad_to_remove, clan_squad_pool);
  2527.                         squad_sz -= mergeSquadWithPool(squad_to_remove, squad_pool);
  2528.  
  2529.  
  2530.                         if (squad_sz > 0)
  2531.                         {
  2532.                             DebugWrite("Did not find empty slots for all members of, " + squad_to_remove, 3);
  2533.                             DebugWrite("Will move them to no-squad spool, " + squad_to_remove, 3);
  2534.                             while (squad_to_remove.getCount() > 0)
  2535.                             {
  2536.                                 PlayerProfile player = squad_to_remove.removeRandomPlayer();
  2537.                                 if (movePlayer(player, player.getTeamId(), 0))
  2538.                                     nosquad_pool.Add(player);
  2539.                             }
  2540.                         }
  2541.  
  2542.                         /* remove the empty squads */
  2543.                         DebugWrite("Removing empty squads", 3);
  2544.                         squad_pool.RemoveAll(delegate(PlayerSquad squad) { return squad.getCount() == 0; });
  2545.                     }
  2546.  
  2547.  
  2548.  
  2549.                 }
  2550.  
  2551.  
  2552.                 DebugWrite("Team(" + TN(neutralTeamId) + ") squad pool before move", 3);
  2553.                 DebugWrite("=====================================================", 3);
  2554.                 List<PlayerSquad> temp_pool = getNonEmptySquads(neutralTeamId);
  2555.                 DebugWrite("Temp pool has ^b" + temp_pool.Count + "^n squads^0", 2);
  2556.                 temp_pool.Sort(new Comparison<PlayerSquad>(getSquadSort("round_sort")));
  2557.                 for (int i = 0; i < squad_pool.Count; i++)
  2558.                 {
  2559.                     DebugWrite("      " + i + ". " + temp_pool[i].ToString() + "(" + getSortFieldValueStr(temp_pool[i], "round_sort") + ")", 3);
  2560.                 }
  2561.  
  2562.  
  2563.                 /* add clan squads to the squad pool */
  2564.                 DebugWrite("Moving ^b" + clan_squad_pool.Count + "^n from clan-squad pool to Team(" + TN(neutralTeamId) + ")", 3);
  2565.                 foreach (PlayerSquad squad in clan_squad_pool)
  2566.                     moveSquad(squad, neutralTeamId, team_sz * 2);
  2567.  
  2568.             }
  2569.  
  2570.             /* re-build the pools */
  2571.  
  2572.             DebugWrite("Rebuilding no-squad pool", 3);
  2573.             nosquad_pool = getNoSquadPlayers(neutralTeamId);
  2574.             DebugWrite("No-squad pool has ^b" + nosquad_pool.Count + "^n player/s^0", 3);
  2575.             listPlayers(nosquad_pool);
  2576.  
  2577.             DebugWrite("Rebuilding squad pool", 3);
  2578.             squad_pool = getNonEmptySquads(neutralTeamId);
  2579.             DebugWrite("Squad pool has ^b" + squad_pool.Count + "^n squads^0", 2);
  2580.  
  2581.  
  2582.             if (squad_pool.Count > max_squads)
  2583.                 ConsoleWrite("^1^bWARNING^0^n: There are still more squads than allowed!");
  2584.  
  2585.             /* sort the no-squad pool */
  2586.             DebugWrite("Sorting the no-squad pool by ^b" + getStringVarValue("round_sort") + "^n^0", 3);
  2587.             nosquad_pool.Sort(new Comparison<PlayerProfile>(getPlayerSort("round_sort")));
  2588.  
  2589.             for (int i = 0; i < nosquad_pool.Count; i++)
  2590.             {
  2591.                 DebugWrite("      " + i + ". " + nosquad_pool[i] + "(" + getSortFieldValueStr(nosquad_pool[i], "round_sort") + ")", 3);
  2592.             }
  2593.  
  2594.  
  2595.             /* sort the squad pool */
  2596.             DebugWrite("Sorting the squad pool by ^b" + getStringVarValue("round_sort") + "^n^0", 3);
  2597.             squad_pool.Sort(new Comparison<PlayerSquad>(getSquadSort("round_sort")));
  2598.  
  2599.             for (int i = 0; i < squad_pool.Count; i++)
  2600.             {
  2601.                 DebugWrite("      " + i + ". " + squad_pool[i].ToString() + "(" + getSortFieldValueStr(squad_pool[i], "round_sort") + ")", 3);
  2602.             }
  2603.  
  2604.             int[] teamCount = new int[3];
  2605.             teamCount[neutralTeamId] = sumSquadPlayers(squad_pool) + nosquad_pool.Count;
  2606.             teamCount[winTeamId] = getPlayerCount()[winTeamId];
  2607.             teamCount[loseTeamId] = getPlayerCount()[loseTeamId];
  2608.  
  2609.             DebugWrite("Team counts, ^bTeam(" + TN(neutralTeamId) + ")^n: " + teamCount[neutralTeamId] + ", ^bTeam(" + TN(winTeamId) + ")^n: " + teamCount[winTeamId] + ", ^bTeam(" + TN(loseTeamId) + ")^n: " + teamCount[loseTeamId], 3);
  2610.  
  2611.             Dictionary<string, int> clanTeam = new Dictionary<string, int>();
  2612.  
  2613.             /* assume the smaller team */
  2614.             int smallTeamId = loseTeamId;
  2615.  
  2616.             DebugWrite("Moving ^b" + squad_pool.Count + "^n squads from neutral ^bTeam(" + TN(neutralTeamId) + ")^n into ^bTeam(" + TN(winTeamId) + ")^n and ^bTeam(" + TN(loseTeamId) + ")^n^0", 3);
  2617.  
  2618.             while (squad_pool.Count > 0)
  2619.             {
  2620.                 /* get the top squad */
  2621.                 PlayerSquad squad = squad_pool[0];
  2622.                 squad_pool.RemoveAt(0);
  2623.  
  2624.                 if (getBooleanVarValue("keep_clans_round"))
  2625.                 {
  2626.                     string tag = squad.getMajorityClanTag();
  2627.                     /* if squad has a clan tag, determine where most of his team is already */
  2628.                     if (!Regex.Match(tag, @"^\s*$").Success)
  2629.                     {
  2630.                         if (clanTeam.ContainsKey(tag))
  2631.                         {
  2632.                             int clan_team_id = clanTeam[tag];
  2633.                             DebugWrite("There is already a clan squad for ^b[" + tag + "]^n in ^bTeam(" + TN(clan_team_id) + ")^n^0", 3);
  2634.                             smallTeamId = clan_team_id;
  2635.                         }
  2636.                         else
  2637.                         {
  2638.                             DebugWrite("First time seeing clan ^b[" + tag + "]^n will assign to ^bTeam(" + TN(smallTeamId) + ")^n^0", 3);
  2639.                             clanTeam.Add(tag, smallTeamId);
  2640.                         }
  2641.                     }
  2642.                 }
  2643.  
  2644.                 int squad_sz = squad.getCount();
  2645.  
  2646.                 /* move top squad to the smaller team */
  2647.                 DebugWrite("Moving entire " + squad.ToString() + " to ^bTeam(" + TN(smallTeamId) + ")^n^0", 3);
  2648.                 /* squad size may change if not all players were moved, i.e. someone was in white list */
  2649.                 squad_sz = moveSquad(squad, smallTeamId, team_sz);
  2650.  
  2651.  
  2652.                 /* update the team counts */
  2653.                 teamCount[smallTeamId] += squad_sz;
  2654.                 teamCount[neutralTeamId] -= squad_sz;
  2655.  
  2656.                 /* determine the smaller team */
  2657.                 smallTeamId = getSmallTeamId(winTeamId, teamCount[winTeamId], loseTeamId, teamCount[loseTeamId]);
  2658.                 DebugWrite("Team counts, ^bTeam(" + TN(neutralTeamId) + ")^n: " + teamCount[neutralTeamId] + ", ^bTeam(" + TN(winTeamId) + ")^n: " + teamCount[winTeamId] + ", ^bTeam(" + TN(loseTeamId) + ")^n: " + teamCount[loseTeamId] + ", ^b Small Team(" + TN(smallTeamId) + ")^n: " + teamCount[smallTeamId], 3);
  2659.                 DebugWrite("------------------------------------------------------------------------------------------------", 3);
  2660.             }
  2661.  
  2662.             DebugWrite("^bTeam(" + TN(winTeamId) + ")^n has now ^b" + teamCount[winTeamId] + "^n player/s", 3);
  2663.             DebugWrite("^bTeam(" + TN(loseTeamId) + ")^n has now ^b" + teamCount[loseTeamId] + "^n player/s", 3);
  2664.  
  2665.             DebugWrite("Moving ^b" + nosquad_pool.Count + "^n player/s from neutral ^bTeam(" + TN(neutralTeamId) + ")^n into ^bTeam(" + TN(winTeamId) + ")^n and ^bTeam(" + TN(loseTeamId) + ")^n^0", 3);
  2666.  
  2667.             while (nosquad_pool.Count > 0)
  2668.             {
  2669.                 /* get the top player */
  2670.                 PlayerProfile player = nosquad_pool[0];
  2671.                 nosquad_pool.RemoveAt(0);
  2672.  
  2673.                 /* move the top player to the smaller team */
  2674.                 DebugWrite("Moving ^b" + player.ToString() + "^n to ^bTeam(^n" + TN(smallTeamId) + ")^n^0", 3);
  2675.                 int moved = 1;
  2676.                 if (!movePlayer(player, smallTeamId, 0, true))
  2677.                     moved = 0;
  2678.  
  2679.                 /* update the team counts */
  2680.                 teamCount[neutralTeamId] -= moved;
  2681.                 teamCount[smallTeamId] += moved;
  2682.  
  2683.                 /* determine the smaller team */
  2684.                 smallTeamId = getSmallTeamId(winTeamId, teamCount[winTeamId], loseTeamId, teamCount[loseTeamId]);
  2685.             }
  2686.  
  2687.  
  2688.             DebugWrite("^bTeam(" + TN(winTeamId) + ")^n has now ^b" + teamCount[winTeamId] + "^n player/s", 3);
  2689.             DebugWrite("^bTeam(" + TN(loseTeamId) + ")^n has now ^b" + teamCount[loseTeamId] + "^n player/s", 3);
  2690.  
  2691.             if (teamsUnbalanced())
  2692.             {
  2693.                 DebugWrite("Teams are still unbalanced, applying the live balancing logic", 3);
  2694.                 balanceLive(utc, true);
  2695.  
  2696.  
  2697.             }
  2698.             else
  2699.                 DebugWrite("Teams should now be balanced!", 3);
  2700.  
  2701.             DebugWrite("Doing sanity check now", 3);
  2702.             DebugWrite("========================", 3);
  2703.  
  2704.             List<PlayerProfile> moving_from_win_to_lose = getPlayersMoving(winTeamId, loseTeamId);
  2705.             List<PlayerProfile> moving_from_lose_to_win = getPlayersMoving(loseTeamId, winTeamId);
  2706.  
  2707.  
  2708.  
  2709.             DebugWrite(moving_from_win_to_lose.Count + " players will be moving from Team(" + TN(winTeamId) + ") to Team(" + TN(loseTeamId) + ")", 3);
  2710.             DebugWrite(moving_from_lose_to_win.Count + " players will be moving from Team(" + TN(loseTeamId) + ") to Team(" + TN(winTeamId) + ")", 3);
  2711.  
  2712.             int teamWithMoreMoving = 0;
  2713.             int players_needing_moving = 0;
  2714.             List<PlayerProfile> players_moving = null;
  2715.  
  2716.             if (moving_from_win_to_lose.Count > moving_from_lose_to_win.Count)
  2717.             {
  2718.                 teamWithMoreMoving = winTeamId;
  2719.                 players_moving = moving_from_win_to_lose;
  2720.                 int slots_needed_in_lose_team = moving_from_win_to_lose.Count - moving_from_lose_to_win.Count;
  2721.                 DebugWrite(slots_needed_in_lose_team + " free slots are needed in Team(" + TN(loseTeamId) + "), and there are " + fslots[loseTeamId], 3);
  2722.                 if (slots_needed_in_lose_team > fslots[loseTeamId])
  2723.                 {
  2724.                     DebugWrite("There are only " + fslots[loseTeamId] + " free slots in Team(" + TN(loseTeamId) + ")", 3);
  2725.                     players_needing_moving = slots_needed_in_lose_team - fslots[loseTeamId];
  2726.                     DebugWrite("Meaning that, " + players_needing_moving + " players will not be able to move from Team(" + TN(winTeamId) + ") to Team(" + TN(loseTeamId) + ")", 3);
  2727.                 }
  2728.             }
  2729.             else if (moving_from_lose_to_win.Count > moving_from_win_to_lose.Count)
  2730.             {
  2731.                 teamWithMoreMoving = loseTeamId;
  2732.                 players_moving = moving_from_lose_to_win;
  2733.                 int slots_needed_in_win_team = moving_from_lose_to_win.Count - moving_from_win_to_lose.Count;
  2734.                 DebugWrite(slots_needed_in_win_team + " free slots are needed in Team(" + TN(winTeamId) + "), and there are " + fslots[winTeamId], 3);
  2735.                 if (slots_needed_in_win_team > fslots[winTeamId])
  2736.                 {
  2737.                     DebugWrite("There are only " + fslots[winTeamId] + " free slots in Team(" + TN(winTeamId) + ")", 3);
  2738.                     players_needing_moving = slots_needed_in_win_team - fslots[winTeamId];
  2739.                     DebugWrite("Meaning that, " + players_needing_moving + " players will not be able to move from Team(" + TN(loseTeamId) + ") to Team(" + TN(winTeamId) + ")", 3);
  2740.                 }
  2741.             }
  2742.  
  2743.             if (players_needing_moving > 0)
  2744.             {
  2745.                 DebugWrite("I have determined that " + players_needing_moving + " players will need to stay in Team(" + TN(teamWithMoreMoving) + ") to remedy this situation", 3);
  2746.  
  2747.                 while (players_needing_moving > 0 && players_moving.Count > 0)
  2748.                 {
  2749.                     PlayerProfile pp = players_moving[0];
  2750.                     players_moving.RemoveAt(0);
  2751.  
  2752.                     /* he already stays, leave him alone */
  2753.                     if (pp.getSavedTeamId() == pp.getTeamId())
  2754.                         continue;
  2755.  
  2756.                     /* move him back to where he was */
  2757.                     players_needing_moving -= mergePlayerWithTeam(pp, pp.getSavedTeamId());
  2758.  
  2759.                 }
  2760.  
  2761.             }
  2762.  
  2763.             DebugWrite("Re-doing sanity check now", 3);
  2764.             DebugWrite("========================", 3);
  2765.  
  2766.             moving_from_win_to_lose = getPlayersMoving(winTeamId, loseTeamId);
  2767.             moving_from_lose_to_win = getPlayersMoving(loseTeamId, winTeamId);
  2768.  
  2769.             DebugWrite(moving_from_win_to_lose.Count + " players will be moving from Team(" + TN(winTeamId) + ") to Team(" + TN(loseTeamId) + ")", 3);
  2770.             DebugWrite(moving_from_lose_to_win.Count + " players will be moving from Team(" + TN(loseTeamId) + ") to Team(" + TN(winTeamId) + ")", 3);
  2771.  
  2772.             virtual_mode = false;
  2773.  
  2774.             /* swap players that are moving across teams only, and put them in no-squad */
  2775.             fixTeams(winTeamId, pcounts, fslots);
  2776.  
  2777.             /* fix the squads for players */
  2778.             sleep = true;
  2779.             fixSquads();
  2780.             sleep = false;
  2781.         }
  2782.  
  2783.  
  2784.  
  2785.         private List<PlayerProfile> getPlayersMoving(int fromTeamId, int toTeamId)
  2786.         {
  2787.             List<PlayerProfile> list = new List<PlayerProfile>();
  2788.             List<PlayerProfile> player_list = getPlayersProfile("");
  2789.  
  2790.             foreach (PlayerProfile pp in player_list)
  2791.                 if (pp.getSavedTeamId() == fromTeamId &&
  2792.                     pp.getTeamId() == toTeamId)
  2793.                     list.Add(pp);
  2794.             return list;
  2795.         }
  2796.  
  2797.  
  2798.  
  2799.  
  2800.         private void balanceLive(DateTime now)
  2801.         {
  2802.             balanceLive(now, false);
  2803.         }
  2804.  
  2805.  
  2806.         private void delayedLiveBalance(DateTime now, bool force)
  2807.         {
  2808.            
  2809.             /* save the original team and squad for each player */
  2810.             List<PlayerProfile> players = getPlayersProfile("");
  2811.             players.ForEach(delegate(PlayerProfile pp)
  2812.             {
  2813.                 if (pp.getDelayedTeamId() > 0)
  2814.                     DebugWrite("Un-flagging ^b" + pp + "^n for delayed move", 3);
  2815.                 pp.resetDelayedTeamSquad();
  2816.                 pp.saveTeamSquad();
  2817.             });
  2818.            
  2819.  
  2820.             live_balancer = true;
  2821.  
  2822.             /* for delayed live balance we want to do it all virtually, and only move players after they respawn */
  2823.             bool original_value = virtual_mode;
  2824.             if (!original_value)
  2825.                 virtual_mode = true;
  2826.  
  2827.            
  2828.  
  2829.             balanceLive(now, force, true);
  2830.             virtual_mode = original_value;
  2831.  
  2832.             ConsoleWrite("virtual live-balance done, proceeding now to flag players that will need moving");
  2833.  
  2834.             /* save the delayed team, and squad for each player */
  2835.             players = getPlayersProfile("");
  2836.             players.ForEach(delegate(PlayerProfile pp)
  2837.             {
  2838.                 if (pp.getSavedTeamId() != pp.getTeamId())
  2839.                 {
  2840.                     /* save the delayed team and squad */
  2841.                     pp.saveDelayedTeamSquad();
  2842.  
  2843.                     /* reset the original team and squad */
  2844.                     pp.setTeamId(pp.getSavedTeamId());
  2845.                     pp.setSquadId(pp.getSavedSquadId());
  2846.  
  2847.                     if (pp.isAlive())
  2848.                     {
  2849.                         DebugWrite("Player ^b" + pp + "^n is alive, flagged for delayed move from ^bTeam(" + TN(pp.getSavedTeamId()) + ").Squad(" + SQN(pp.getSavedSquadId()) + ")^n to ^bDTeam(" + TN(pp.getDelayedTeamId()) + ").DSquad(" + SQN(pp.getDelayedSquadId()) + ")^n", 3);
  2850.                     }
  2851.                     else
  2852.                     {
  2853.                         DebugWrite("Player ^b" + pp + "^n "+playerstate2stringED(pp.state)+", flagged for immediate move from ^bTeam(" + TN(pp.getSavedTeamId()) + ").Squad(" + SQN(pp.getSavedSquadId()) + ")^n to ^bDTeam(" + TN(pp.getDelayedTeamId()) + ").DSquad(" + SQN(pp.getDelayedSquadId()) + ")^n", 3);    
  2854.                         /* skip balance check, we alreay know teams are not balanced */
  2855.                         enforceImmediateMove(pp);
  2856.                     }
  2857.                 }
  2858.                 pp.resetSavedTeamSquad();
  2859.             });
  2860.            
  2861.            
  2862.             live_balancer = false;
  2863.         }
  2864.  
  2865.         private void balanceLive(DateTime now, bool force)
  2866.         {
  2867.             if (getBooleanVarValue("wait_death"))
  2868.             {
  2869.                 ConsoleWrite("^bwait_death^n is ^bon^n, will do live-balance in virtual mode");
  2870.                 delayedLiveBalance(now, force);
  2871.             }
  2872.             else
  2873.             {
  2874.                 ConsoleWrite("^bwait_death^n is ^boff^n, will do live-balance on the fly");
  2875.                 balanceLive(now, force, false);
  2876.             }
  2877.         }
  2878.  
  2879.         private void balanceLive(DateTime now, bool force, bool delayed)
  2880.         {
  2881.             try
  2882.             {
  2883.                 if (round_balancer && !force)
  2884.                 {
  2885.                     ConsoleWrite("Cannot run live balancer, round-balancing is active");
  2886.                     return;
  2887.                 }
  2888.  
  2889.                 if (balanceTeams(now) > 0 && getBooleanVarValue("keep_clans_live"))
  2890.                 {
  2891.                     ConsoleWrite("Re-running live balancer, with ^bkeep_clans_live^n disabled");
  2892.                     setBooleanVarValue("keep_clans_live", false);
  2893.                     if (balanceTeams(now) > 0 && getBooleanVarValue("use_white_list"))
  2894.                     {
  2895.                         ConsoleWrite("Re-running live balancer, with ^buse_white_list^n disabled");
  2896.                         setBooleanVarValue("use_white_list", false);
  2897.                         balanceTeams(now);
  2898.                         setBooleanVarValue("use_white_list", true);
  2899.                     }
  2900.                     setBooleanVarValue("keep_clans_live", true);
  2901.                 }
  2902.             }
  2903.             catch (Exception e)
  2904.             {
  2905.                 dump_exception(e);
  2906.             }
  2907.         }
  2908.  
  2909.  
  2910.         private bool vacateTeamSlot(List<PlayerProfile> list, PlayerProfile source)
  2911.         {
  2912.             source.visited = true;
  2913.             int noSquadId = 0;
  2914.             if (source == null)
  2915.                 return true;
  2916.  
  2917.  
  2918.             if (source.getSavedTeamId() == source.getTargetTeamId() &&
  2919.                 source.getSavedSquadId() == source.getTargetSquadId())
  2920.             {
  2921.                 //player will not move, slot not vacated
  2922.                 return false;
  2923.             }
  2924.  
  2925.             foreach (PlayerProfile pp in list)
  2926.             {
  2927.                 if (pp.visited == true)
  2928.                     continue;
  2929.  
  2930.                 if (source.getTargetTeamId() == pp.getTeamId() &&
  2931.                     pp.getTargetTeamId() == source.getTeamId())
  2932.                 {
  2933.                     if (vacateTeamSlot(list, pp))
  2934.                     {
  2935.                         DebugWrite("Moving " + source + " to from STeam(" + TN(source.getSavedTeamId()) + ").SSquad(" + SQN(source.getSavedSquadId()) + ") to TTeam(" + TN(source.getTargetTeamId()) + ").TSquad(" + SQN(noSquadId) + ")", 3);
  2936.                         movePlayer(source, source.getTargetTeamId(), noSquadId, false, true);
  2937.                         return true;
  2938.                     }
  2939.                 }
  2940.  
  2941.             }
  2942.  
  2943.             DebugWrite("Final moving " + source + " to from STeam(" + TN(source.getSavedTeamId()) + ").SSquad(" + SQN(source.getSavedSquadId()) + ") to TTeam(" + TN(source.getTargetTeamId()) + ").TSquad(" + SQN(noSquadId) + ")", 3);
  2944.             movePlayer(source, source.getTargetTeamId(), noSquadId, false, true);
  2945.             return true;
  2946.         }
  2947.  
  2948.         private void fixSquads()
  2949.         {
  2950.  
  2951.         }
  2952.  
  2953.         private void fixTeams(int winTeamId, Dictionary<int, int> pcounts, Dictionary<int, int> fslots)
  2954.         {
  2955.             int loseTeamId = getOpposingTeamId(winTeamId);
  2956.             int neutralTeamId = 0;
  2957.             int noSquadId = 0;
  2958.  
  2959.             DebugWrite("====================================================================", 3);
  2960.             DebugWrite("Virtual calculations done, now proceeding to actually move players!", 3);
  2961.             List<PlayerProfile> players_list = getPlayersProfile("");
  2962.  
  2963.             /* save everyone's target team and squad */
  2964.             players_list.ForEach(delegate(PlayerProfile p) { p.saveTargetTeamSquad(); });
  2965.  
  2966.             /* get players moving across teams */
  2967.             List<PlayerProfile> moving_from_win_to_lose = getPlayersMoving(winTeamId, loseTeamId);
  2968.             List<PlayerProfile> moving_from_lose_to_win = getPlayersMoving(loseTeamId, winTeamId);
  2969.  
  2970.             DebugWrite(moving_from_win_to_lose.Count + " players will be moving from Team(" + TN(winTeamId) + ") to Team(" + TN(loseTeamId) + ")", 3);
  2971.             DebugWrite(moving_from_lose_to_win.Count + " players will be moving from Team(" + TN(loseTeamId) + ") to Team(" + TN(winTeamId) + ")", 3);
  2972.  
  2973.             /* get aggreagte moving across teams */
  2974.             List<PlayerProfile> all_moving = new List<PlayerProfile>();
  2975.             all_moving.AddRange(moving_from_win_to_lose);
  2976.             all_moving.AddRange(moving_from_lose_to_win);
  2977.             DebugWrite("Total of " + all_moving.Count + " players will be moving across teams", 3);
  2978.  
  2979.             /* get players staying in their own team */
  2980.             List<PlayerProfile> staying_in_win = getPlayersMoving(winTeamId, winTeamId);
  2981.             List<PlayerProfile> staying_in_lose = getPlayersMoving(loseTeamId, loseTeamId);
  2982.  
  2983.             DebugWrite(staying_in_win.Count + " players will be staying in Team(" + TN(winTeamId) + ")", 3);
  2984.             DebugWrite(staying_in_lose.Count + " players will be staying in Team(" + TN(loseTeamId) + ")", 3);
  2985.  
  2986.             /* aggregate players staying in their own team */
  2987.             List<PlayerProfile> all_staying = new List<PlayerProfile>();
  2988.             all_staying.AddRange(staying_in_win);
  2989.             all_staying.AddRange(staying_in_lose);
  2990.             DebugWrite("Total of " + all_staying.Count + " players will be staying in their own team", 3);
  2991.  
  2992.  
  2993.  
  2994.             List<PlayerProfile> all_players = new List<PlayerProfile>();
  2995.             all_players.AddRange(all_moving);
  2996.             all_players.AddRange(all_staying);
  2997.             DebugWrite("Total of " + all_players.Count + " in server", 3);
  2998.  
  2999.  
  3000.             DebugWrite("Swapping players that move across Team(" + TN(winTeamId) + ") and Team(" + TN(loseTeamId) + ")", 3);
  3001.             DebugWrite("Team(" + TN(winTeamId) + ") has " + fslots[winTeamId] + " free slots", 3);
  3002.             DebugWrite("Team(" + TN(loseTeamId) + ") has " + fslots[loseTeamId] + " free slots", 3);
  3003.  
  3004.  
  3005.             int teamWithMostFreeSlots = 0;
  3006.             int teamWithLeastFreeSlots = 0;
  3007.             List<PlayerProfile> teamToChooseFromFirst = null;
  3008.             List<PlayerProfile> teamToChooseFromSecond = null;
  3009.  
  3010.             if (fslots[winTeamId] > fslots[loseTeamId])
  3011.             {
  3012.                 teamWithMostFreeSlots = winTeamId;
  3013.                 teamWithLeastFreeSlots = loseTeamId;
  3014.                 teamToChooseFromFirst = moving_from_lose_to_win;
  3015.                 teamToChooseFromSecond = moving_from_win_to_lose;
  3016.  
  3017.                 DebugWrite("Team(" + TN(teamWithMostFreeSlots) + ") has the most free slots", 3);
  3018.  
  3019.             }
  3020.             else if (fslots[loseTeamId] > fslots[winTeamId])
  3021.             {
  3022.                 teamWithMostFreeSlots = loseTeamId;
  3023.                 teamWithLeastFreeSlots = winTeamId;
  3024.                 teamToChooseFromFirst = moving_from_win_to_lose;
  3025.                 teamToChooseFromSecond = moving_from_lose_to_win;
  3026.  
  3027.                 DebugWrite("Team(" + TN(teamWithMostFreeSlots) + ") has the most free slots", 3);
  3028.             }
  3029.             else
  3030.             {
  3031.                 teamWithMostFreeSlots = winTeamId;
  3032.                 teamWithLeastFreeSlots = loseTeamId;
  3033.                 teamToChooseFromFirst = moving_from_lose_to_win;
  3034.                 teamToChooseFromSecond = moving_from_win_to_lose;
  3035.                 DebugWrite("Both Team(" + TN(winTeamId) + ") and Team(" + TN(loseTeamId) + " have same number of free slots", 3);
  3036.             }
  3037.  
  3038.  
  3039.             DebugWrite("I will start the swapping from Team(" + TN(teamWithLeastFreeSlots) + ") to Team(" + TN(teamWithMostFreeSlots) + ")", 3);
  3040.  
  3041.             while (teamToChooseFromFirst.Count > 0 && teamToChooseFromSecond.Count > 0)
  3042.             {
  3043.                 PlayerProfile player_first = teamToChooseFromFirst[0];
  3044.                 PlayerProfile player_second = teamToChooseFromSecond[0];
  3045.                 teamToChooseFromFirst.RemoveAt(0);
  3046.                 teamToChooseFromSecond.RemoveAt(0);
  3047.  
  3048.                 DebugWrite("Swapping" + player_first + " from Team(" + TN(player_first.getSavedTeamId()) + ") with " + player_second + " from Team(" + TN(player_second.getSavedTeamId()) + ")", 3);
  3049.  
  3050.                 PlayerProfile pp = player_first;
  3051.                 DebugWrite("Moving " + pp + " to from STeam(" + TN(pp.getSavedTeamId()) + ").SSquad(" + SQN(pp.getSavedSquadId()) + ") to TTeam(" + TN(pp.getTargetTeamId()) + ").TSquad(" + SQN(noSquadId) + ")", 3);
  3052.                 movePlayer(player_first, player_first.getTargetTeamId(), noSquadId, true, true);
  3053.  
  3054.                 pp = player_second;
  3055.                 DebugWrite("Moving " + pp + " to from STeam(" + TN(pp.getSavedTeamId()) + ").SSquad(" + SQN(pp.getSavedSquadId()) + ") to TTeam(" + TN(pp.getTargetTeamId()) + ").TSquad(" + SQN(noSquadId) + ")", 3);
  3056.                 movePlayer(player_second, player_second.getTargetTeamId(), noSquadId, true, true);
  3057.  
  3058.                 DebugWrite("-------------------------------------------------------------------------------------------------------------------------", 3);
  3059.             }
  3060.  
  3061.             int teamIdWithRemainingPlayer = 0;
  3062.             List<PlayerProfile> teamWithRemainingPlayer = new List<PlayerProfile>();
  3063.  
  3064.             if (teamToChooseFromFirst.Count > teamToChooseFromSecond.Count)
  3065.             {
  3066.                 teamIdWithRemainingPlayer = teamWithMostFreeSlots;
  3067.                 teamWithRemainingPlayer = teamToChooseFromFirst;
  3068.             }
  3069.             else if (teamToChooseFromSecond.Count > teamToChooseFromFirst.Count)
  3070.             {
  3071.                 teamIdWithRemainingPlayer = teamWithLeastFreeSlots;
  3072.                 teamWithRemainingPlayer = teamToChooseFromSecond;
  3073.             }
  3074.  
  3075.             if (teamWithRemainingPlayer.Count > 0)
  3076.             {
  3077.                 DebugWrite("There are still " + teamWithRemainingPlayer.Count + " in Team(" + TN(teamIdWithRemainingPlayer) + ") to be moved", 3);
  3078.  
  3079.                 foreach (PlayerProfile pp in teamWithRemainingPlayer)
  3080.                 {
  3081.                     DebugWrite("Moving " + pp + " to from STeam(" + TN(pp.getSavedTeamId()) + ").SSquad(" + SQN(pp.getSavedSquadId()) + ") to TTeam(" + TN(pp.getTargetTeamId()) + ").TSquad(" + SQN(noSquadId) + ")", 3);
  3082.                     movePlayer(pp, pp.getTargetTeamId(), noSquadId, true, true);
  3083.                     DebugWrite("-------------------------------------------------------------------------------------------------------------------------", 3);
  3084.                 }
  3085.             }
  3086.  
  3087.  
  3088.  
  3089.  
  3090.             List<PlayerProfile> move = new List<PlayerProfile>();
  3091.             /* move all players to no-squad, unless they are already in the no-squad, or they are already in their final position */
  3092.  
  3093.             DebugWrite("Fixing squad positions, will only move players that are switching squads", 3);
  3094.  
  3095.             DebugWrite("First putting players in Squad(" + SQN(noSquadId) + "), using " + all_staying.Count + " players that did not move across teams", 3);
  3096.             foreach (PlayerProfile pp in all_staying)
  3097.             {
  3098.                 /* skip players that are already in squad 0 anyways */
  3099.                 if (pp.getSavedSquadId() == 0)
  3100.                     continue;
  3101.  
  3102.                 /* skip players that are already in their final position */
  3103.                 if (pp.getSavedSquadId() == pp.getTargetSquadId())
  3104.                     continue;
  3105.  
  3106.                 DebugWrite("Moving " + pp + " to from STeam(" + TN(pp.getSavedTeamId()) + ").SSquad(" + SQN(pp.getSavedSquadId()) + ") to TTeam(" + TN(pp.getTargetTeamId()) + ").TSquad(" + SQN(noSquadId) + ")", 3);
  3107.                 if (pp.getTargetSquadId() == 0)
  3108.                 {
  3109.                     /* after this move, this player end in its final position, no need to move him anymore*/
  3110.                     movePlayer(pp, pp.getTargetTeamId(), noSquadId, true, true);
  3111.                     continue;
  3112.                 }
  3113.  
  3114.                 movePlayer(pp, pp.getTargetTeamId(), noSquadId, true, true);
  3115.                 move.Add(pp);
  3116.             }
  3117.  
  3118.             move.AddRange(all_moving);
  3119.  
  3120.             /* now put all players in their destination squad */
  3121.             DebugWrite("Now putting players in their final squads, using a set of " + move.Count + " players", 3);
  3122.             foreach (PlayerProfile pp in move)
  3123.             {
  3124.                 /* skip players that are already in their final position */
  3125.                 if (pp.getSavedSquadId() == pp.getTargetSquadId())
  3126.                     continue;
  3127.  
  3128.                 DebugWrite("Moving " + pp + " to from STeam(" + TN(pp.getTeamId()) + ").SSquad(" + SQN(pp.getSquadId()) + ") to TTeam(" + TN(pp.getTargetTeamId()) + ").TSquad(" + SQN(pp.getTargetSquadId()) + ")", 3);
  3129.                 movePlayer(pp, pp.getTargetTeamId(), pp.getTargetSquadId(), true, true);
  3130.             }
  3131.         }
  3132.  
  3133.         private void getClanSquads(List<PlayerProfile> members, Dictionary<string, List<PlayerSquad>> clan_squads, Dictionary<string, int> clan_stats)
  3134.         {
  3135.             int neutralTeamId = 0;
  3136.             int noSquadId = 0;
  3137.             int max_squad_size = 4;
  3138.             int max_squads = 16;
  3139.  
  3140.             members.RemoveAll(delegate(PlayerProfile player)
  3141.             {
  3142.                 /* if player is not in a clan, ignore it*/
  3143.                 if (!player.isInClan())
  3144.                     return false;
  3145.  
  3146.  
  3147.  
  3148.                 string tag = player.getClanTag();
  3149.  
  3150.                 /* if less than two players for the clan, ignore it */
  3151.  
  3152.                 if (clan_stats[tag] < 2)
  3153.                     return false;
  3154.  
  3155.                 /* count total number of squads */
  3156.                 int total = 0;
  3157.                 foreach (KeyValuePair<string, List<PlayerSquad>> pair in clan_squads)
  3158.                     total += pair.Value.Count;
  3159.  
  3160.                 if (!clan_squads.ContainsKey(tag))
  3161.                     clan_squads[tag] = new List<PlayerSquad>();
  3162.  
  3163.                 List<PlayerSquad> squads = clan_squads[tag];
  3164.  
  3165.                 /* if there is no squads, of they are all full, add a new at the end */
  3166.                 if (squads.Count == 0 || squads[squads.Count - 1].getCount() == max_squad_size)
  3167.                 {
  3168.                     if (total >= max_squads)
  3169.                     {
  3170.                         if (squads.Count == 0)
  3171.                             clan_squads.Remove(tag);
  3172.  
  3173.                         DebugWrite(player + " ignored, max squads count reached", 3);
  3174.                         return false;
  3175.                     }
  3176.                     squads.Add(new PlayerSquad(neutralTeamId, getNextFreeClanSquadId(clan_squads)));
  3177.                 }
  3178.  
  3179.                 /* add player to the last squad in the clan */
  3180.                 if (movePlayer(player, neutralTeamId, squads[squads.Count - 1].getSquadId(), true))
  3181.                     squads[squads.Count - 1].addPlayer(player);
  3182.  
  3183.                 return true;
  3184.             });
  3185.         }
  3186.  
  3187.         private int getNextFreeClanSquadId(Dictionary<string, List<PlayerSquad>> clan_squads)
  3188.         {
  3189.             int count = 1;
  3190.             foreach (KeyValuePair<string, List<PlayerSquad>> pair in clan_squads)
  3191.                 foreach (PlayerSquad squad in pair.Value)
  3192.                     count++;
  3193.  
  3194.             return 16 + count;
  3195.         }
  3196.  
  3197.         private void getClanStats(List<PlayerProfile> members, Dictionary<string, int> stats)
  3198.         {
  3199.             foreach (PlayerProfile player in members)
  3200.             {
  3201.                 if (!player.isInClan())
  3202.                     continue;
  3203.  
  3204.                 string tag = player.getClanTag();
  3205.  
  3206.                 if (!stats.ContainsKey(tag))
  3207.                     stats[tag] = 0;
  3208.  
  3209.                 stats[tag]++;
  3210.             }
  3211.         }
  3212.  
  3213.         private void getClanStatsByTeam(List<PlayerProfile> members, Dictionary<string, int>[] stats)
  3214.         {
  3215.             for (int i = 0; i < members.Count; i++)
  3216.             {
  3217.                 PlayerProfile player = members[i];
  3218.                 if (!player.isInClan())
  3219.                     continue;
  3220.  
  3221.                 string tag = player.getClanTag();
  3222.                 int teamId = player.getTeamId();
  3223.                 int oppositeTeamId = getOpposingTeamId(teamId);
  3224.  
  3225.                 if (!stats[teamId].ContainsKey(tag))
  3226.                     stats[teamId].Add(tag, 0);
  3227.  
  3228.                 if (!stats[oppositeTeamId].ContainsKey(tag))
  3229.                     stats[oppositeTeamId].Add(tag, 0);
  3230.  
  3231.  
  3232.                 stats[teamId][tag]++;
  3233.             }
  3234.         }
  3235.  
  3236.  
  3237.         private int getSmallTeamId(int team1Id, int team1Count, int team2Id, int team2Count)
  3238.         {
  3239.             return (team1Count < team2Count) ? team1Id : team2Id;
  3240.         }
  3241.  
  3242.         private int getBigTeamId(int team1Id, int team1Count, int team2Id, int team2Count)
  3243.         {
  3244.             return (team1Count > team2Count) ? team1Id : team2Id;
  3245.         }
  3246.  
  3247.         private int getOpposingTeamId(int teamId)
  3248.         {
  3249.             return (teamId == 0) ? teamId : (teamId == 1) ? 2 : 1;
  3250.         }
  3251.  
  3252.  
  3253.  
  3254.  
  3255.  
  3256.         private int balanceTeams(DateTime now)
  3257.         {
  3258.  
  3259.  
  3260.             pluginState = PluginState.balance;
  3261.             setStartTime(pluginState, now.AddSeconds(1));
  3262.             DebugWrite("^b" + pluginState + "_live^n state started " + getStartTime(pluginState).ToString() + "^n^0", 1);
  3263.  
  3264.             bool keep_clans = getBooleanVarValue("keep_clans_live");
  3265.             Dictionary<int, int> player_count = getPlayerCount();
  3266.  
  3267.             if (player_count[1] == player_count[2])
  3268.                 return 0;
  3269.  
  3270.             int team_sz = serverInfo.MaxPlayerCount / 2;
  3271.             int neutral_team = 0;
  3272.             int bigger_team = (player_count[1] > player_count[2]) ? 1 : 2;
  3273.             int smaller_team = (player_count[1] > player_count[2]) ? 2 : 1;
  3274.             int total = player_count[1] + player_count[2];
  3275.             int difference = Math.Abs(player_count[1] - player_count[2]);
  3276.             int needed = difference / 2;
  3277.  
  3278.  
  3279.             DebugWrite("Total of ^b" + total + "^n player/s in server^0", 3);
  3280.             for (int i = 1; i < 3; i++)
  3281.             {
  3282.                 DebugWrite("^bTeam(" + TN(i) + ")^n has ^b" + player_count[i] + "^n player/s^0", 3);
  3283.             }
  3284.  
  3285.             DebugWrite("Teams differ by ^b" + difference + "^n player/s,  ^b" + needed + "^n player/s are needed on ^bTeam(" + TN(smaller_team) + ")^n^0", 3);
  3286.  
  3287.             DebugWrite("Building no-squad pool from ^bTeam(" + TN(bigger_team) + ")^n^0", 3);
  3288.             List<PlayerProfile> nosquad_pool = getNoSquadPlayers(bigger_team);
  3289.             DebugWrite("No-squad pool has ^b" + nosquad_pool.Count + "^n player/s^0", 3);
  3290.  
  3291.             DebugWrite("Building squad pool from ^bTeam(" + TN(bigger_team) + ")^n^0", 3);
  3292.             List<PlayerSquad> squad_pool = getNonEmptySquads(bigger_team);
  3293.             DebugWrite("Squad pool has ^b" + squad_pool.Count + "^n squads^0", 3);
  3294.  
  3295.  
  3296.             Dictionary<string, int>[] clan_stats = new Dictionary<string, int>[3];
  3297.             clan_stats[smaller_team] = new Dictionary<string, int>();
  3298.             clan_stats[bigger_team] = new Dictionary<string, int>();
  3299.             clan_stats[neutral_team] = new Dictionary<string, int>();
  3300.  
  3301.             if (keep_clans)
  3302.             {
  3303.                 DebugWrite("Keeping clans in same team", 3);
  3304.  
  3305.                 List<PlayerProfile> players_list = getPlayersProfile("");
  3306.                 /* collect statistics about clans */
  3307.                 DebugWrite("Collecting clan statistics", 3);
  3308.                 getClanStatsByTeam(players_list, clan_stats);
  3309.  
  3310.  
  3311.                 List<string> clanlist = new List<string>();
  3312.                 clanlist.AddRange(clan_stats[1].Keys);
  3313.  
  3314.                 DebugWrite("^b" + clanlist.Count + "^n clans in server: [^b" + String.Join("^n], [^b", clanlist.ToArray()) + "^n]", 3);
  3315.             }
  3316.  
  3317.             if (!getBooleanVarValue("keep_squads_live"))
  3318.             {
  3319.                 DebugWrite("^bkeep_squads_live^n is off, moving players to no-squad pool before balancing", 3);
  3320.                 foreach (PlayerSquad squad in squad_pool)
  3321.                     foreach (PlayerProfile player in squad.getMembers())
  3322.                         nosquad_pool.Add(player);
  3323.  
  3324.                 squad_pool.Clear();
  3325.             }
  3326.  
  3327.             /* sort the no-squad pool */
  3328.             DebugWrite("Sorting the no-squad pool by ^b" + getStringVarValue("live_sort") + "^n^0", 3);
  3329.             nosquad_pool.Sort(new Comparison<PlayerProfile>(getPlayerSort("live_sort")));
  3330.  
  3331.             for (int i = 0; i < nosquad_pool.Count; i++)
  3332.                 DebugWrite("      " + i + ". " + nosquad_pool[i] + "(" + getSortFieldValueStr(nosquad_pool[i], "live_sort") + ")", 3);
  3333.  
  3334.  
  3335.             DebugWrite("Moving ^b" + needed + "^n players from sorted no-squad pool to ^bTeam(" + TN(smaller_team) + ")^n^0", 3);
  3336.             while (needed > 0 && nosquad_pool.Count > 0)
  3337.             {
  3338.                 PlayerProfile player = nosquad_pool[0];
  3339.                 nosquad_pool.RemoveAt(0);
  3340.                 string tag = player.getClanTag();
  3341.  
  3342.                 /* if keeping clans together, and there are more than two players in the clan in the sever */
  3343.                 if (keep_clans && shouldSkipClanPlayer(player, smaller_team, bigger_team, clan_stats))
  3344.                      continue;
  3345.  
  3346.                 DebugWrite("Moving ^b" + player.ToString() + "^n to ^bTeam(^n" + TN(smaller_team) + ")^n^0", 3);
  3347.                 if (movePlayer(player, smaller_team, 0, true))
  3348.                     needed--;
  3349.             }
  3350.  
  3351.             /* if teams are balanced, we are done */
  3352.             if (needed == 0)
  3353.             {
  3354.                 DebugWrite("Teams should now be balanced!", 3);
  3355.                 return needed;
  3356.             }
  3357.  
  3358.             /* teams are not balanced, proceed on squad balancing */
  3359.  
  3360.             DebugWrite("Teams are still unbalanced, " + needed + " more player/s needed", 3);
  3361.  
  3362.             /* sort the squad pool */
  3363.             DebugWrite("Sorting the squad pool by ^b" + getStringVarValue("live_sort") + "^n^0", 3);
  3364.             squad_pool.Sort(new Comparison<PlayerSquad>(getSquadSort("live_sort")));
  3365.  
  3366.             for (int i = 0; i < squad_pool.Count; i++)
  3367.             {
  3368.                 DebugWrite("      " + i + ". " + squad_pool[i].ToString() + "(" + getSortFieldValueStr(squad_pool[i], "live_sort") + ")", 3);
  3369.             }
  3370.  
  3371.             DebugWrite("Moving squads from sorted squad pool to ^bTeam(" + TN(smaller_team) + ")^n^0", 3);
  3372.             while (needed > 0 && squad_pool.Count > 0)
  3373.             {
  3374.                 PlayerSquad squad = squad_pool[0];
  3375.                 squad_pool.RemoveAt(0);
  3376.  
  3377.  
  3378.                 int squad_sz = squad.getCount();
  3379.                 string squad_uid = squad.ToString();
  3380.                 string smaller_team_uid = "^bTeam(" + TN(smaller_team) + ")^n";
  3381.  
  3382.                 DebugWrite("^b" + needed + "^n players are needed on " + smaller_team_uid + "^0", 3);
  3383.                 DebugWrite(squad_uid + " has ^b" + squad_sz + "^n player/s^0", 2);
  3384.  
  3385.                 if (needed >= squad_sz)
  3386.                 {
  3387.                     if (keep_clans && shouldSkipClanSquad(squad, smaller_team, bigger_team, clan_stats))
  3388.                         continue;
  3389.  
  3390.                    
  3391.                     /* we can move the entrie squad */
  3392.                     DebugWrite("Moving entire " + squad_uid + " to " + smaller_team_uid + "^0", 3);
  3393.                     squad_sz = moveSquad(squad, smaller_team, team_sz);
  3394.                     needed -= squad_sz;
  3395.                 }
  3396.                 else
  3397.                 {
  3398.                     /* we have to break up a squad */
  3399.                     PlayerSquad temp_squad = new PlayerSquad(squad.getTeamId(), squad.getSquadId());
  3400.  
  3401.                     DebugWrite("Breaking up " + squad_uid + " to get ^b" + needed + "^n player/s^0", 3);
  3402.                     DebugWrite("But, first I will sort the members of " + squad_uid, 3);
  3403.                     squad.sortMembers(getPlayerSort("live_sort"));
  3404.                     for (int i = 0; i < squad.getCount(); i++)
  3405.                         DebugWrite("      " + i + ". " + squad.getMembers()[i] + "(" + getSortFieldValueStr(squad.getMembers()[i], "live_sort") + ")", 3);
  3406.  
  3407.                     /* get as many players as needed */
  3408.                     while (needed > 0 && squad.getCount() > 0)
  3409.                     {
  3410.                         PlayerProfile player = squad.getMembers()[0];
  3411.                         squad.dropPlayer(player);
  3412.  
  3413.                         if (keep_clans && shouldSkipClanPlayer(player, smaller_team, bigger_team, clan_stats))
  3414.                             continue;
  3415.  
  3416.                         if (isInMoveWhiteList(player))
  3417.                             continue;
  3418.  
  3419.                         temp_squad.addPlayer(player);
  3420.                         DebugWrite("Player " + player + " selected to move to " + smaller_team_uid + "^0", 3);
  3421.                         needed--;
  3422.                     }
  3423.  
  3424.                     /* move the temporary squad */
  3425.                     moveSquad(temp_squad, smaller_team, team_sz);
  3426.                 }
  3427.             }
  3428.  
  3429.  
  3430.             if (needed == 0)
  3431.                 DebugWrite("Teams should now be balanced!", 3);
  3432.             else
  3433.                 DebugWrite("Teams are still ubalanced!", 3);
  3434.  
  3435.             return needed;
  3436.         }
  3437.  
  3438.         private bool shouldSkipClanSquad(PlayerSquad squad, int smaller_team, int bigger_team, Dictionary<string, int>[] clan_stats)
  3439.         {
  3440.             int squad_sz = squad.getCount();
  3441.             string tag = squad.getMajorityClanTag();
  3442.  
  3443.             if (tag.Length > 0 && (clan_stats[bigger_team][tag] + clan_stats[smaller_team][tag]) > 1)
  3444.             {
  3445.                 if (clan_stats[bigger_team][tag] >= clan_stats[smaller_team][tag])
  3446.                 {
  3447.                     DebugWrite("Skipping clan-squad " + squad.ToString() + " because majority of clan is in same team", 3);
  3448.                     return true;
  3449.                 }
  3450.  
  3451.                 /* update clan stats */
  3452.                 clan_stats[bigger_team][tag] -= squad_sz;
  3453.                 clan_stats[smaller_team][tag] += squad_sz;
  3454.             }
  3455.  
  3456.             return false;
  3457.         }
  3458.  
  3459.         private bool shouldSkipClanPlayer(PlayerProfile player, int smaller_team, int bigger_team, Dictionary<string, int>[] clan_stats)
  3460.         {
  3461.             string tag = player.getClanTag();
  3462.  
  3463.             if (!clan_stats[bigger_team].ContainsKey(tag))
  3464.                 clan_stats[bigger_team].Add(tag, 0);
  3465.  
  3466.             if (!clan_stats[smaller_team].ContainsKey(tag))
  3467.                 clan_stats[smaller_team].Add(tag, 0);
  3468.  
  3469.             if (player.isInClan() && (clan_stats[bigger_team][tag] + clan_stats[smaller_team][tag]) > 1)
  3470.             {
  3471.                 /* if the majority of the players in the clan are in this team, skip this player */
  3472.                 if (clan_stats[bigger_team][tag] >= clan_stats[smaller_team][tag])
  3473.                 {
  3474.                     DebugWrite("Skipping clan-player ^b" + player + "^n because majority of clan is in his team", 3);
  3475.                     return true;
  3476.                 }
  3477.  
  3478.                 /* update the clan stats */
  3479.                 clan_stats[bigger_team][tag]--;
  3480.                 clan_stats[smaller_team][tag]++;
  3481.             }
  3482.             return false;
  3483.         }
  3484.  
  3485.         private string getSortFieldValueStr(PlayerProfile player, string phase)
  3486.         {
  3487.             string sort_method = getStringVarValue(phase);
  3488.  
  3489.             if (sort_method.CompareTo("kdr_asc_round") == 0 || sort_method.CompareTo("kdr_desc_round") == 0)
  3490.                 return "kdr_round: " + Math.Round(player.getRoundKdr(), 2);
  3491.             else if (sort_method.CompareTo("score_asc_round") == 0 || sort_method.CompareTo("score_desc_round") == 0)
  3492.                 return "score_round: " + Math.Round(player.getRoundScore(), 2);
  3493.             else if (sort_method.CompareTo("spm_asc_round") == 0 || sort_method.CompareTo("spm_desc_round") == 0)
  3494.                 return "spm_round: " + Math.Round(player.getRoundSpm(), 2);
  3495.             else if (sort_method.CompareTo("kpm_asc_round") == 0 || sort_method.CompareTo("kpm_desc_round") == 0)
  3496.                 return "kpm_round: " + Math.Round(player.getRoundKpm(), 2);
  3497.             else if (sort_method.CompareTo("time_asc_round") == 0 || sort_method.CompareTo("time_desc_round") == 0)
  3498.                 return "time_round: " + player.getRoundTime();
  3499.  
  3500.  
  3501.             ConsoleWrite("^1^bWARNING^0^n: annot find player sort method for ^b" + sort_method + "^0");
  3502.             return "";
  3503.         }
  3504.  
  3505.         private string getSortFieldValueStr(PlayerSquad squad, string phase)
  3506.         {
  3507.             string sort_method = getStringVarValue(phase);
  3508.  
  3509.             if (sort_method.CompareTo("kdr_asc_round") == 0 || sort_method.CompareTo("kdr_desc_round") == 0)
  3510.                 return "kdr_round: " + Math.Round(squad.getRoundKdr(), 2);
  3511.             else if (sort_method.CompareTo("score_asc_round") == 0 || sort_method.CompareTo("score_desc_round") == 0)
  3512.                 return "score_round: " + Math.Round(squad.getRoundScore(), 2);
  3513.             else if (sort_method.CompareTo("spm_asc_round") == 0 || sort_method.CompareTo("spm_desc_round") == 0)
  3514.                 return "spm_round: " + Math.Round(squad.getRoundSpm(), 2);
  3515.             else if (sort_method.CompareTo("kpm_asc_round") == 0 || sort_method.CompareTo("kpm_desc_round") == 0)
  3516.                 return "kpm_round: " + Math.Round(squad.getRoundKpm(), 2);
  3517.             else if (sort_method.CompareTo("time_asc_round") == 0 || sort_method.CompareTo("time_desc_round") == 0)
  3518.                 return "time_round: " + squad.getRoundTime();
  3519.  
  3520.             ConsoleWrite("^1^bWARNING^0^n: cannot find squad sort method for ^b" + sort_method + "^0");
  3521.             return "";
  3522.         }
  3523.  
  3524.         private bool movePlayer(PlayerProfile player, int teamId, int squadId, bool force)
  3525.         {
  3526.             return movePlayer(player, teamId, squadId, force, false);
  3527.         }
  3528.  
  3529.         private bool movePlayer(PlayerProfile player, int teamId, int squadId)
  3530.         {
  3531.             return movePlayer(player, teamId, squadId, false, false);
  3532.         }
  3533.  
  3534.         private bool isInMoveWhiteList(PlayerProfile player)
  3535.         {
  3536.             return isPlayerInWhiteList(player, "player_move_wlist") || isPlayerInWhiteList(player, "clan_move_wlist") ||
  3537.                    isPlayerInWhiteList(player, "player_safe_wlist") || isPlayerInWhiteList(player, "clan_safe_wlist");
  3538.         }
  3539.  
  3540.         private bool isInKickWhiteList(PlayerProfile player)
  3541.         {
  3542.             return isPlayerInWhiteList(player, "player_kick_wlist") || isPlayerInWhiteList(player, "clan_kick_wlist") ||
  3543.                    isPlayerInWhiteList(player, "player_safe_wlist") || isPlayerInWhiteList(player, "clan_safe_wlist");
  3544.         }
  3545.        
  3546.  
  3547.         private bool isPlayerInWhiteList(PlayerProfile player, String list_name)
  3548.         {
  3549.             if (!getBooleanVarValue("use_white_list"))
  3550.                 return false;
  3551.  
  3552.             if (!getPluginVars().Contains(list_name))
  3553.             {
  3554.                 ConsoleWrite("^1^bWARNING: ^n^0 unknown white list ^b"+list_name+"^n");
  3555.                 return false;
  3556.             }
  3557.  
  3558.             List<String> whitelist = getStringListVarValue(list_name);
  3559.             if (whitelist.Count == 0)
  3560.                 return false;
  3561.  
  3562.             String field = "";
  3563.             if (Regex.Match(list_name, @"clan").Success)
  3564.                 field = player.getClanTag();
  3565.             else if (Regex.Match(list_name, @"player").Success)
  3566.                 field = player.name;
  3567.             else
  3568.             {
  3569.                 ConsoleWrite("^1^bWARNING:^0^n white list ^b" + list_name + "^n does not contain 'player' or 'clan' sub-string");
  3570.                 return false;
  3571.             }
  3572.  
  3573.             if (Regex.Match(field, @"^\s*$").Success)
  3574.                 return false;
  3575.  
  3576.             return whitelist.Contains(field);
  3577.         }
  3578.  
  3579.  
  3580.         private bool movePlayer(PlayerProfile player, int teamId, int squadId, bool force, bool ignore_white_list)
  3581.         {
  3582.             if (player == null)
  3583.                 return false;
  3584.  
  3585.             if (!force && player.getTeamId() == teamId && player.getSquadId() == squadId)
  3586.             {
  3587.                 ConsoleWrite("^1^bWARNING^0^n: not moving ^b" + player + "^n to same Team(" + TN(teamId) + ").Squad(" + SQN(squadId) + ")");
  3588.                 return false;
  3589.             }
  3590.             else if (!ignore_white_list && isInMoveWhiteList(player))
  3591.             {
  3592.                 ConsoleWrite("^b" + player.ToString() + "^n in white-list, will not move to Team(" + TN(teamId) + ").Squad(" + SQN(squadId) + ")");
  3593.                 return false;
  3594.             }
  3595.  
  3596.  
  3597.             /* firt move player to the no-squad, to guarantee a spot (unless he is already goin to the no-squad, or stays in same team) */
  3598.             if ((squadId != 0 || player.getTeamId() != teamId) && !(virtual_mode || getBooleanVarValue("virtual_mode")))
  3599.             {
  3600.                 if (sleep)
  3601.                     Thread.Sleep(100);
  3602.                 ExecCommand("admin.movePlayer", player.name, teamId.ToString(), "0", "true");
  3603.             }
  3604.  
  3605.             /* in virtual mode, don't actually do the move */
  3606.             if (!(virtual_mode || getBooleanVarValue("virtual_mode")))
  3607.             {
  3608.                 if (sleep)
  3609.                     Thread.Sleep(100);
  3610.                 ExecCommand("admin.movePlayer", player.name, teamId.ToString(), squadId.ToString(), "true");
  3611.             }
  3612.             player.setTeamId(teamId);
  3613.             player.setSquadId(squadId);
  3614.             return true;
  3615.         }
  3616.  
  3617.  
  3618.         /* best effort to move an entire squad into another team withouth breaking up */
  3619.  
  3620.         private int moveSquad(PlayerSquad squad, int teamId, int team_sz)
  3621.         {
  3622.             int players_moved = 0;
  3623.             if (squad == null)
  3624.                 return 0;
  3625.  
  3626.             /* first move all players to the opposite team without squad (to guarantee a spot)*/
  3627.             int squadId = 0;
  3628.             int noSquadId = 0;
  3629.  
  3630.  
  3631.             List<PlayerProfile> squad_players = squad.getMembers();
  3632.  
  3633.             /* find a squad on teamId with enough space */
  3634.             List<PlayerSquad> squads = getAllSquads(teamId);
  3635.  
  3636.  
  3637.             /* find first empty squad */
  3638.  
  3639.             foreach (PlayerSquad sq in squads)
  3640.             {
  3641.                 if (sq.getCount() == 0)
  3642.                 {
  3643.                     DebugWrite("Found empty squad " + sq + ", for " + squad, 3);
  3644.                     while (squad.getCount() > 0)
  3645.                     {
  3646.                         PlayerProfile pp = squad.removeRandomPlayer();
  3647.                         DebugWrite("Moving ^b" + pp + "^n to Team(" + TN(teamId) + ").Squad(" + SQN(sq.getSquadId()) + ")", 3);
  3648.                         if (movePlayer(pp, teamId, sq.getSquadId()))
  3649.                             players_moved++;
  3650.  
  3651.                     }
  3652.                     break;
  3653.                 }
  3654.             }
  3655.  
  3656.             if (squad.getCount() == 0)
  3657.                 return players_moved;
  3658.  
  3659.             ConsoleWrite("^1^bWARNING^0^n: Could not find an empty squad on ^bTeam(" + TN(teamId) + ")^n for " + squad.ToString());
  3660.             ConsoleWrite("Looking now for squads that are not full^n");
  3661.  
  3662.             /* sort the squads in increasing order of player count */
  3663.  
  3664.             squads.Sort(new Comparison<PlayerSquad>(squad_count_asc_cmp));
  3665.  
  3666.             for (int i = 0; i < squads.Count; i++)
  3667.             {
  3668.                 PlayerSquad sorted_squad = squads[i];
  3669.                 if (sorted_squad.getSquadId() > 8)
  3670.                     continue;
  3671.  
  3672.                 if (sorted_squad.getFreeSlots() > 0 && squad_players.Count > 0)
  3673.                     DebugWrite("Found " + sorted_squad.getFreeSlots() + " free slots on " + sorted_squad, 3);
  3674.  
  3675.                 while (sorted_squad.getFreeSlots() > 0 && squad_players.Count > 0)
  3676.                 {
  3677.                     PlayerProfile squad_player = squad_players[0];
  3678.                     squad_players.RemoveAt(0);
  3679.                     DebugWrite("Moving ^b" + squad_player + "^n to Team(" + TN(teamId) + ").Squad(" + SQN(sorted_squad.getSquadId()) + ")", 3);
  3680.                     if (movePlayer(squad_player, teamId, sorted_squad.getSquadId()))
  3681.                         players_moved++;
  3682.                 }
  3683.             }
  3684.  
  3685.             foreach (PlayerProfile pp in squad_players)
  3686.             {
  3687.                 ConsoleWrite("^1^bWARNING^0^n: could not find squad on ^bTeam(" + TN(teamId) + ")^n for ^b" + pp + "^n^0");
  3688.                 DebugWrite("Moving ^b" + pp + "^n to Team(" + TN(teamId) + ").Squad(" + SQN(noSquadId) + ")", 3);
  3689.                 if (movePlayer(pp, teamId, noSquadId))
  3690.                     players_moved++;
  3691.             }
  3692.  
  3693.             return players_moved;
  3694.  
  3695.         }
  3696.  
  3697.         private List<PlayerProfile> removePlayers(List<PlayerProfile> player_list, int max_size)
  3698.         {
  3699.             if (players == null || players.Count == 0)
  3700.             {
  3701.                 ConsoleWrite("^1^bWARNING^0^n: cannot make a squad without any players");
  3702.                 return null;
  3703.             }
  3704.  
  3705.             List<PlayerProfile> removed = new List<PlayerProfile>();
  3706.             while (player_list.Count > 0 && removed.Count <= max_size)
  3707.             {
  3708.                 removed.Add(player_list[0]);
  3709.                 player_list.RemoveAt(0);
  3710.             }
  3711.  
  3712.             return removed;
  3713.         }
  3714.  
  3715.  
  3716.         public Dictionary<int, int> getPlayerCount()
  3717.         {
  3718.  
  3719.             /* initialize hash with player count for 16 teams*/
  3720.             Dictionary<int, int> player_count = new Dictionary<int, int>();
  3721.             for (int i = 0; i < 16; i++)
  3722.                 player_count[i] = 0;
  3723.  
  3724.             List<PlayerProfile> player_list = getPlayersProfile("");
  3725.  
  3726.             foreach (PlayerProfile player in player_list)
  3727.                 player_count[player.getTeamId()]++;
  3728.  
  3729.  
  3730.             return player_count;
  3731.         }
  3732.  
  3733.  
  3734.  
  3735.         private List<PlayerProfile> getNoSquadPlayers(int teamId)
  3736.         {
  3737.             Dictionary<int, PlayerSquad> squads = getSquads(teamId);
  3738.             /* return the members of the no-squad */
  3739.             return squads[0].getMembers();
  3740.         }
  3741.  
  3742.  
  3743.         private List<PlayerSquad> getAllSquads(int teamId)
  3744.         {
  3745.             Dictionary<int, PlayerSquad> squads = getSquads(teamId);
  3746.  
  3747.             /* remove the no-squad */
  3748.             squads.Remove(0);
  3749.  
  3750.             List<PlayerSquad> list = new List<PlayerSquad>();
  3751.             foreach (KeyValuePair<int, PlayerSquad> pair in squads)
  3752.                 list.Add(pair.Value);
  3753.  
  3754.             return list;
  3755.         }
  3756.  
  3757.  
  3758.  
  3759.         private List<PlayerSquad> getNonEmptySquads(int teamId)
  3760.         {
  3761.             Dictionary<int, PlayerSquad> squads = getSquads(teamId);
  3762.  
  3763.             /* remove the no-squad */
  3764.             squads.Remove(0);
  3765.  
  3766.             /* get only the non-empty squads */
  3767.             List<PlayerSquad> list = new List<PlayerSquad>();
  3768.             foreach (KeyValuePair<int, PlayerSquad> pair in squads)
  3769.                 if (pair.Value.getCount() > 0)
  3770.                     list.Add(pair.Value);
  3771.  
  3772.             return list;
  3773.         }
  3774.  
  3775.         private void listSquad(PlayerSquad sq)
  3776.         {
  3777.             List<PlayerProfile> members = sq.getMembers();
  3778.  
  3779.             DebugWrite("Team(^b" + TN(sq.getTeamId()) + "^n).Squad(^b" + SQN(sq.getSquadId()) + "^n): " + sq.getCount() + " players", 3);
  3780.             int count = 1;
  3781.             foreach (PlayerProfile pp in members)
  3782.                 DebugWrite("    " + count++ + ".  ^b" + pp + "^n", 3);
  3783.         }
  3784.  
  3785.         private void listSquads(List<PlayerSquad> sqs)
  3786.         {
  3787.             foreach (PlayerSquad sq in sqs)
  3788.                 listSquad(sq);
  3789.         }
  3790.  
  3791.         private Dictionary<int, PlayerSquad> getSquads(int teamId)
  3792.         {
  3793.             int num_squads = 8;
  3794.             if (teamId == 0)
  3795.                 num_squads = 16;
  3796.  
  3797.             List<PlayerProfile> player_list = getPlayersProfile("");
  3798.  
  3799.             Dictionary<int, PlayerSquad> squads = new Dictionary<int, PlayerSquad>();
  3800.             for (int i = 0; i <= num_squads; i++)
  3801.                 squads[i] = new PlayerSquad(teamId, i);
  3802.  
  3803.             foreach (PlayerProfile player in player_list)
  3804.             {
  3805.                 if (player.getTeamId() == teamId && squads.ContainsKey(player.getSquadId()))
  3806.                     squads[player.getSquadId()].addPlayer(player);
  3807.             }
  3808.  
  3809.             return squads;
  3810.         }
  3811.  
  3812.         private bool isTimeLeft(int remain_time, int msg_display_time, int msg_interval_time, int countdown_time)
  3813.         {
  3814.             return (remain_time % msg_interval_time) == 0 && (remain_time - msg_display_time) >= countdown_time;
  3815.         }
  3816.  
  3817.         public bool isServerEmpty()
  3818.         {
  3819.             return players.Count == 0;
  3820.         }
  3821.  
  3822.         public void forwardTicks(int count)
  3823.         {
  3824.             utc = utc.AddSeconds(count);
  3825.         }
  3826.  
  3827.  
  3828.         public void ConsoleWrite(string msg)
  3829.         {
  3830.             string prefix = "[^b" + GetPluginName() + "^n] ";
  3831.             this.ExecuteCommand("procon.protected.pluginconsole.write", prefix + msg);
  3832.         }
  3833.  
  3834.         public void DebugWrite(string msg, int level)
  3835.         {
  3836.             if (getIntegerVarValue("debug_level") >= level)
  3837.                 ConsoleWrite(msg);
  3838.         }
  3839.  
  3840.         public void OnPluginDisable()
  3841.         {
  3842.             ConsoleWrite("^b^1Disabled =(^0");
  3843.  
  3844.             plugin_enabled = false;
  3845.  
  3846.             unloadSettings();
  3847.  
  3848.         }
  3849.  
  3850.         public String getPluginVariableGroup(String name)
  3851.         {
  3852.             foreach (KeyValuePair<String, List<String>> group_pair in settings_group)
  3853.                 if (group_pair.Value.Contains(name))
  3854.                     return group_pair.Key;
  3855.  
  3856.             return "Settings";
  3857.         }
  3858.  
  3859.         public int getGroupOrder(String name)
  3860.         {
  3861.             //if (settings_group_order.ContainsKey(name))
  3862.             //    return settings_group_order[name];
  3863.  
  3864.  
  3865.             Dictionary<int, String> reverse = new Dictionary<int, string>();
  3866.             foreach (KeyValuePair<String, int> pair in settings_group_order)
  3867.                 reverse.Add(pair.Value, pair.Key);
  3868.  
  3869.             int offset = 0;
  3870.             for (int i = 0; i <= reverse.Count; i++)
  3871.                 if (!reverse.ContainsKey(i))
  3872.                     continue;
  3873.                 else
  3874.                 {
  3875.                     if (shouldSkipGroup(reverse[i]))
  3876.                         continue;
  3877.                     offset++;
  3878.                     if (name.Equals(reverse[i]))
  3879.                         return offset;
  3880.                 }
  3881.            
  3882.  
  3883.             return offset;
  3884.         }
  3885.  
  3886.         public bool shouldSkipGroup(String name)
  3887.         {
  3888.  
  3889.             if ((name.Equals("Round Balancer") || name.Equals("Round Interval")) && !getBooleanVarValue("balance_round"))
  3890.                 return true;
  3891.  
  3892.             if (name.Equals("Live Balancer") && !getBooleanVarValue("balance_live"))
  3893.                 return true;
  3894.  
  3895.             if (name.Equals("Whitelist") && !getBooleanVarValue("use_white_list"))
  3896.                 return true;
  3897.  
  3898.             return false;
  3899.  
  3900.         }
  3901.  
  3902.         public bool shouldSkipVariable(String name)
  3903.         {
  3904.  
  3905.             if (Regex.Match(name, @"^(?:player|clan)_(?:move|kick)_wlist").Success && !getBooleanVarValue("use_extra_white_lists"))
  3906.                 return true;
  3907.  
  3908.             return false;
  3909.            
  3910.         }
  3911.  
  3912.         public List<CPluginVariable> GetDisplayPluginVariables()
  3913.         {
  3914.             List<CPluginVariable> lstReturn = new List<CPluginVariable>();
  3915.  
  3916.  
  3917.  
  3918.             //lstReturn.Add(new CPluginVariable("Settings|Refresh", typeof(string), "| edit this field to refresh settings |"));
  3919.  
  3920.             List<string> vars = getPluginVars(true);
  3921.  
  3922.  
  3923.  
  3924.      
  3925.  
  3926.             foreach (string var_name in vars)
  3927.             {
  3928.                 String group_name = getPluginVariableGroup(var_name);
  3929.                 String var_type = "string";
  3930.                 String var_value = getPluginVarValue(var_name);
  3931.                 int group_order = getGroupOrder(group_name);
  3932.  
  3933.                 if (shouldSkipGroup(group_name))
  3934.                     continue;
  3935.  
  3936.                 if (shouldSkipVariable(var_name))
  3937.                     continue;
  3938.                
  3939.                 if (var_name.Equals("live_sort") || var_name.Equals("round_sort"))
  3940.                     var_type = "enum." + var_name + "(" + String.Join("|", getAllowedSorts().ToArray()) + ")";
  3941.                 else if (var_name.Equals("pass"))
  3942.                     var_value = Regex.Replace(getPluginVarValue(var_name), @".", "*");
  3943.  
  3944.                 lstReturn.Add(new CPluginVariable(group_order + ". " + group_name + "|" + var_name, var_type, var_value));
  3945.             }
  3946.  
  3947.             return lstReturn;
  3948.         }
  3949.  
  3950.         //Lists all of the plugin variables.
  3951.         public List<CPluginVariable> GetPluginVariables()
  3952.         {
  3953.             List<CPluginVariable> lstReturn = new List<CPluginVariable>();
  3954.  
  3955.             List<string> vars = getPluginVars();
  3956.             foreach (string var in vars)
  3957.                 lstReturn.Add(new CPluginVariable(var, typeof(string), getPluginVarValue(var)));
  3958.  
  3959.             return lstReturn;
  3960.         }
  3961.  
  3962.  
  3963.         public void SetPluginVariable(string var, string val)
  3964.         {
  3965.             //ConsoleWrite("setting " + var + " to " + val);
  3966.             if (var.ToLower().Contains("refresh"))
  3967.                 return;
  3968.  
  3969.  
  3970.  
  3971.  
  3972.  
  3973.             setPluginVarValue(var, val);
  3974.  
  3975.  
  3976.         }
  3977.  
  3978.  
  3979.         public void OnPlayerJoin(string strSoldierName)
  3980.         {
  3981.             battleLogConnect();
  3982.         }
  3983.  
  3984.         public void OnPlayerKilled(Kill killInfo)
  3985.         {    
  3986.            
  3987.             if (killInfo == null)
  3988.                 return;
  3989.  
  3990.             CPlayerInfo killer = killInfo.Killer;
  3991.             CPlayerInfo victim = killInfo.Victim;
  3992.  
  3993.             PlayerProfile vp = getPlayerProfile(victim.SoldierName);
  3994.             PlayerProfile kp = getPlayerProfile(killer.SoldierName);
  3995.  
  3996.             if (vp != null)
  3997.             {
  3998.                 vp.state = PlayerState.dead;
  3999.                 vp.updateInfo(victim);
  4000.                 vp.updateLastDeath();
  4001.  
  4002.                 if (vp.getDelayedTeamId() > 0)
  4003.                 {
  4004.                     DebugWrite("Player " + vp + " has died, he was flagged to be moved to ^bDTeam(" + TN(vp.getDelayedTeamId()) + ").DSquad(" + SQN(vp.getDelayedSquadId()) + ")^n", 3);
  4005.                     /* do not skip the balance check, this is delayed move, teams may already be balanced */
  4006.                     enforceDelayedMove(vp);
  4007.                 }
  4008.             }
  4009.  
  4010.             if (kp != null)
  4011.             {
  4012.                 kp.updateInfo(killer);
  4013.                 kp.updateLastKill();
  4014.             }
  4015.         }
  4016.  
  4017.         private void enforceDelayedMove(PlayerProfile vp)
  4018.         {
  4019.  
  4020.             int dtid = vp.getDelayedTeamId();
  4021.             int dsid = vp.getDelayedSquadId();
  4022.  
  4023.             vp.resetDelayedTeamSquad();
  4024.  
  4025.             /* if player is already in the delayed team, ignore him */
  4026.             if (dtid == vp.getTeamId())
  4027.             {
  4028.                 DebugWrite("Player " + vp + " is already in to ^bDTeam(" + TN(dtid) + ")^n, will skip", 3);
  4029.                 return;
  4030.             }
  4031.  
  4032.  
  4033.             /* if teams are already balanced, ignore this player */
  4034.             DebugWrite("I will now re-check if teams are balanced", 3);
  4035.             if (teamsBalanced())
  4036.             {
  4037.                 DebugWrite("Teams are balanced, will not move player " + vp, 3);
  4038.                 return;
  4039.             }
  4040.  
  4041.             DebugWrite("Moving player " + vp + " from ^bTeam(" + TN(vp.getTeamId()) + ").Squad(" + SQN(vp.getSquadId()) + ")^n to ^bDTeam(" + TN(dtid) + ").DSquad(" + SQN(dsid) + ")^n", 3);
  4042.             movePlayer(vp, dtid, dsid);
  4043.  
  4044.         }
  4045.  
  4046.         private void enforceImmediateMove(PlayerProfile vp)
  4047.         {
  4048.  
  4049.             int dtid = vp.getDelayedTeamId();
  4050.             int dsid = vp.getDelayedSquadId();
  4051.  
  4052.             vp.resetDelayedTeamSquad();
  4053.  
  4054.             DebugWrite("Moving player " + vp + " from ^bTeam(" + TN(vp.getSavedTeamId()) + ").Squad(" + SQN(vp.getSavedSquadId()) + ")^n to ^bDTeam(" + TN(dtid) + ").DSquad(" + SQN(dsid) + ")^n", 3);
  4055.             movePlayer(vp, dtid, dsid);
  4056.  
  4057.         }
  4058.  
  4059.  
  4060.  
  4061.  
  4062.         public void battleLogConnect()
  4063.         {
  4064.             if (!blog.isReady())
  4065.             {
  4066.                 String[] credentials = getMailPass();
  4067.                 if (credentials != null && attempts < 2)
  4068.                 {
  4069.                     ConsoleWrite("Attempting to sign-in to battlelog.com as ^b" + credentials[0]);
  4070.                     attempts++;
  4071.  
  4072.                     if (blog.connect())
  4073.                         blog.authenticate(credentials[0], credentials[1]);
  4074.                 }
  4075.             }
  4076.         }
  4077.  
  4078.  
  4079.         public void OnPlayerLeft(string strSoldierName)
  4080.         {
  4081.             PlayerProfile player = getPlayerProfile(strSoldierName);
  4082.             if (player != null)
  4083.                 player.state = PlayerState.left;
  4084.            
  4085.             if (this.players.ContainsKey(strSoldierName))
  4086.                 this.players.Remove(strSoldierName);
  4087.                    
  4088.         }
  4089.  
  4090.         public virtual void OnPlayerKickedByAdmin(string soldierName, string reason)
  4091.         {
  4092.             PlayerProfile player = getPlayerProfile(soldierName);
  4093.             if (player != null)
  4094.             {
  4095.                 player.state = PlayerState.kicked;
  4096.                 this.players.Remove(player.name);
  4097.             }
  4098.         }
  4099.  
  4100.         public virtual void OnPlayerMovedByAdmin(string soldierName, int destinationTeamId, int destinationSquadId, bool forceKilled)
  4101.         {
  4102.             PlayerProfile player = getPlayerProfile(soldierName);
  4103.             if (player == null)
  4104.                 return;
  4105.            
  4106.             player.state = PlayerState.dead;
  4107.            
  4108.         }
  4109.  
  4110.  
  4111.  
  4112.         public void OnGlobalChat(string strSpeaker, string strMessage)
  4113.         {
  4114.             if (isInGameCommand(strMessage))
  4115.                 inGameCommand(strSpeaker, strMessage);
  4116.  
  4117.             PlayerProfile player = getPlayerProfile(strSpeaker);
  4118.             if (player != null)
  4119.                 player.updateLastChat();
  4120.         }
  4121.  
  4122.  
  4123.         public void OnTeamChat(string strSpeaker, string strMessage, int iTeamID)
  4124.         {
  4125.             if (isInGameCommand(strMessage))
  4126.                 inGameCommand(strSpeaker, strMessage);
  4127.  
  4128.             PlayerProfile player = getPlayerProfile(strSpeaker);
  4129.             if (player != null)
  4130.                 player.updateLastChat();
  4131.         }
  4132.  
  4133.  
  4134.         public void OnSquadChat(string strSpeaker, string strMessage, int iTeamID, int iSquadID)
  4135.         {
  4136.             if (isInGameCommand(strMessage))
  4137.                 inGameCommand(strSpeaker, strMessage);
  4138.  
  4139.             PlayerProfile player = getPlayerProfile(strSpeaker);
  4140.             if (player != null)
  4141.                 player.updateLastChat();
  4142.         }
  4143.  
  4144.  
  4145.         private bool isInGameCommand(string str)
  4146.         {
  4147.             if (Regex.Match(str, @"^\s*[@/!]").Success)
  4148.                 return true;
  4149.  
  4150.             return false;
  4151.         }
  4152.  
  4153.         public void OnLevelStarted()
  4154.         {
  4155.             DebugWrite("Level starting!", 3);
  4156.             level_started = true;
  4157.         }
  4158.  
  4159.  
  4160.         public void OnPunkbusterplayerStatsCmd(CPunkbusterInfo cpbiPlayer)
  4161.         {
  4162.  
  4163.  
  4164.             if (cpbiPlayer == null)
  4165.                 return;
  4166.  
  4167.             battleLogConnect();
  4168.  
  4169.             if (this.players.ContainsKey(cpbiPlayer.SoldierName))
  4170.                 this.players[cpbiPlayer.SoldierName].pbinfo = cpbiPlayer;
  4171.             else
  4172.                 this.players.Add(cpbiPlayer.SoldierName, new PlayerProfile(this, cpbiPlayer));
  4173.  
  4174.         }
  4175.  
  4176.  
  4177.  
  4178.         public void OnServerInfo(CServerInfo csiServerInfo)
  4179.         {
  4180.             this.serverInfo = csiServerInfo;
  4181.         }
  4182.  
  4183.  
  4184.  
  4185.         public void OnPlayerTeamChange(string soldierName, int teamId, int squadId)
  4186.         {
  4187.             PlayerProfile player = getPlayerProfile(soldierName);
  4188.             if (player == null)
  4189.                 return;
  4190.  
  4191.             player.state = PlayerState.dead;
  4192.             player.setTeamId(teamId);
  4193.             player.setSquadId(squadId);
  4194.            
  4195.         }
  4196.  
  4197.  
  4198.         public void OnPlayerSquadChange(string strSoldierName, int iTeamID, int iSquadID)
  4199.         {
  4200.             PlayerProfile player = getPlayerProfile(strSoldierName);
  4201.             if (player == null)
  4202.                 return;
  4203.  
  4204.             player.setSquadId(iSquadID);
  4205.             player.setTeamId(iTeamID);
  4206.         }
  4207.  
  4208.         public void OnplayersStatsCmd(List<CPlayerInfo> lstPlayers, CPlayerSubset cpsSubset)
  4209.         {
  4210.  
  4211.             if (cpsSubset.Subset == CPlayerSubset.PlayerSubsetType.All)
  4212.                 foreach (CPlayerInfo cpiPlayer in lstPlayers)
  4213.                     if (this.players.ContainsKey(cpiPlayer.SoldierName))
  4214.                         this.players[cpiPlayer.SoldierName].updateInfo(cpiPlayer);
  4215.  
  4216.             /* fail safe to get the maximum number of players in server */
  4217.             if (lstPlayers.Count > max_player_count)
  4218.                 max_player_count = lstPlayers.Count;
  4219.         }
  4220.  
  4221.  
  4222.         public int getPerMapInterval()
  4223.         {
  4224.  
  4225.             String key = getPerMapKey();
  4226.  
  4227.             if (key.Length > 0)
  4228.                 return getIntegerVarValue(key);
  4229.  
  4230.             return 0;
  4231.         }
  4232.  
  4233.         public String getPerMapKey()
  4234.         {
  4235.             string mode = serverInfo.GameMode.ToLower().Trim();
  4236.             string map = serverInfo.Map.ToLower().Trim();
  4237.  
  4238.             if (maps.ContainsKey(map) && modes.ContainsKey(mode))
  4239.                 return modes[mode] + "_" + maps[map];
  4240.  
  4241.             return "";
  4242.         }
  4243.  
  4244.         public bool checkRoundBalance()
  4245.         {
  4246.             int round_interval = this.getIntegerVarValue("round_interval");
  4247.             int round_total = serverInfo.TotalRounds;
  4248.             int round_current = serverInfo.CurrentRound + 1;
  4249.             string map = serverInfo.Map.ToLower();
  4250.  
  4251.             int per_map_interval = getPerMapInterval();
  4252.  
  4253.             /* if user set a value per-map, use that instead */
  4254.             if (per_map_interval > 0)
  4255.             {
  4256.                 ConsoleWrite("Using round_interval value of " + per_map_interval + " for map " + getPerMapKey());
  4257.                 round_interval = per_map_interval;
  4258.             }
  4259.  
  4260.             if (round_interval > round_total)
  4261.             {
  4262.                 ConsoleWrite("^1^bWARNING^0^n: ^bround_interval(" + round_interval + ")^n is greater than total ^brounds(" + round_total + ")^n for ^bmap(" + map + ")^n^0");
  4263.                 ConsoleWrite("setting ^bround_interval^n to ^b" + round_total + "^n internally for ^bmap(" + map + ")^n^0");
  4264.                 round_interval = round_total;
  4265.             }
  4266.  
  4267.  
  4268.             ConsoleWrite("End of round detected");
  4269.             ConsoleWrite("Current round is ^b" + round_current + "^n/^b" + round_total + "^n,");
  4270.             ConsoleWrite("Round balance interval is ^b" + round_interval + "^n^0");
  4271.  
  4272.             if (round_current % round_interval == 0)
  4273.                 return true;
  4274.  
  4275.             return false;
  4276.         }
  4277.  
  4278.  
  4279.         public static string TN(int teamNo)
  4280.         {
  4281.  
  4282.             switch (teamNo)
  4283.             {
  4284.                 case 0:
  4285.                     return "Neutral";
  4286.                 case 1:
  4287.                     return "US";
  4288.                 case 2:
  4289.                     return "RU";
  4290.                 default:
  4291.                     return "Unknown";
  4292.             }
  4293.         }
  4294.  
  4295.  
  4296.         public static string SQN(int squadNo)
  4297.         {
  4298.  
  4299.             switch (squadNo)
  4300.             {
  4301.                 case 0:
  4302.                     return "Neutral";
  4303.                 case 1:
  4304.                     return "Alpha";
  4305.                 case 2:
  4306.                     return "Bravo";
  4307.                 case 3:
  4308.                     return "Charlie";
  4309.                 case 4:
  4310.                     return "Delta";
  4311.                 case 5:
  4312.                     return "Echo";
  4313.                 case 6:
  4314.                     return "Foxtrot";
  4315.                 case 7:
  4316.                     return "Golf";
  4317.                 case 8:
  4318.                     return "Hotel";
  4319.                 case 9:
  4320.                     return "India";
  4321.                 case 10:
  4322.                     return "Juliet";
  4323.                 case 11:
  4324.                     return "Kilo";
  4325.                 case 12:
  4326.                     return "Lima";
  4327.                 case 13:
  4328.                     return "Mike";
  4329.                 case 14:
  4330.                     return "November";
  4331.                 case 15:
  4332.                     return "Oscar";
  4333.                 case 16:
  4334.                     return "Papa";
  4335.                 case 17:
  4336.                     return "X-Alpha";
  4337.                 case 18:
  4338.                     return "X-Bravo";
  4339.                 case 19:
  4340.                     return "X-Charlie";
  4341.                 case 20:
  4342.                     return "X-Delta";
  4343.                 case 21:
  4344.                     return "X-Echo";
  4345.                 case 22:
  4346.                     return "X-Foxtrot";
  4347.                 case 23:
  4348.                     return "X-Golf";
  4349.                 case 24:
  4350.                     return "X-Hotel";
  4351.                 case 25:
  4352.                     return "X-India";
  4353.                 case 26:
  4354.                     return "X-Juliet";
  4355.                 case 27:
  4356.                     return "X-Kilo";
  4357.                 case 28:
  4358.                     return "X-Lima";
  4359.                 case 29:
  4360.                     return "X-Mike";
  4361.                 case 30:
  4362.                     return "X-November";
  4363.                 case 31:
  4364.                     return "X-Oscar";
  4365.                 case 32:
  4366.                     return "X-Papa";
  4367.  
  4368.                 default:
  4369.                     if (squadNo > 16 && squadNo <= 32)
  4370.                         return "S-" + squadNo;
  4371.                     else
  4372.                         return "Unknown";
  4373.             }
  4374.         }
  4375.  
  4376.         public double getRoundMinutes()
  4377.         {
  4378.             return utc.Subtract(startRoundTime).TotalMinutes;
  4379.         }
  4380.  
  4381.  
  4382.         public void delayedRoundBalance()
  4383.         {
  4384.             bool original_state = getBooleanVarValue("balance_live");
  4385.  
  4386.             if (original_state)
  4387.             {
  4388.                 ConsoleWrite("Temporarily disabling live balancer, for round-over");
  4389.                 setBooleanVarValue("balance_live", false);
  4390.             }
  4391.  
  4392.             try
  4393.             {
  4394.  
  4395.                 Thread.Sleep(getIntegerVarValue("round_wait_time") * 1000);
  4396.  
  4397.                 ConsoleWrite("roun-over, ^b" + getIntegerVarValue("round_wait_time") + "^n seconds wait time expired");
  4398.                 if (round_balancer)
  4399.                     balanceRound(win_teamId);
  4400.                 restartWaitState(utc);
  4401.                 resetPlayerStats();
  4402.                 round_balancer = false;
  4403.  
  4404.             }
  4405.             catch (Exception e)
  4406.             {
  4407.                 dump_exception(e);
  4408.             }
  4409.  
  4410.  
  4411.             if (original_state)
  4412.             {
  4413.                 ConsoleWrite("Re-enabling live balancing");
  4414.                 setBooleanVarValue("balance_live", true);
  4415.             }
  4416.         }
  4417.  
  4418.         public void OnRoundOver(int iWinningTeamID)
  4419.         {
  4420.             round_balancer = checkRoundBalance();
  4421.             win_teamId = iWinningTeamID;
  4422.             lose_teamId = getOpposingTeamId(win_teamId);
  4423.             level_started = true;
  4424.  
  4425.  
  4426.             ConsoleWrite("round-over, waiting for ^b" + getIntegerVarValue("round_wait_time") + "^n seconds");
  4427.             Thread sleeper = new Thread(new ThreadStart(delayedRoundBalance));
  4428.             sleeper.Start();
  4429.  
  4430.         }
  4431.  
  4432.         public override void OnPlayerSpawned(string soldierName, Inventory spawnedInventory)
  4433.         {
  4434.             PlayerProfile player = getPlayerProfile(soldierName);
  4435.             if (player != null)
  4436.             {
  4437.                 player.updateLastSpawn();
  4438.                 player.state = PlayerState.alive;
  4439.             }
  4440.  
  4441.         }
  4442.  
  4443.  
  4444.         private void resetPlayerStats()
  4445.         {
  4446.  
  4447.             List<PlayerProfile> players_list = getPlayersProfile("");
  4448.             foreach (PlayerProfile player in players_list)
  4449.             {
  4450.                 player.resetStats();
  4451.             }
  4452.  
  4453.             /* reset the fail-safe counter */
  4454.             max_player_count = 0;
  4455.  
  4456.         }
  4457.  
  4458.  
  4459.  
  4460.         private void SendPlayerMessage(string soldierName, string message)
  4461.         {
  4462.             if (getBooleanVarValue("quiet_mode") && !isAdmin(soldierName))
  4463.                 return;
  4464.  
  4465.             if (soldierName == null)
  4466.                 return;
  4467.  
  4468.             ExecCommand("admin.say", message, "player", soldierName);
  4469.         }
  4470.  
  4471.  
  4472.         private void SendGlobalMessage(string message)
  4473.         {
  4474.             if (getBooleanVarValue("quiet_mode"))
  4475.                 SendConsoleMessage(message);
  4476.             else
  4477.                 ExecCommand("admin.say", message, "all");
  4478.  
  4479.         }
  4480.  
  4481.         private void SendConsoleMessage(string name, string msg)
  4482.         {
  4483.             List<string> admin_list = getAdminList();
  4484.  
  4485.             ConsoleWrite(msg);
  4486.             msg = Regex.Replace(msg, @"\^[0-9a-zA-Z]", "");
  4487.  
  4488.             if (name != null)
  4489.                 SendPlayerMessage(name, msg);
  4490.  
  4491.  
  4492.         }
  4493.  
  4494.         private void SendConsoleMessage(string msg)
  4495.         {
  4496.             List<string> admin_list = getAdminList();
  4497.             ConsoleWrite(msg);
  4498.  
  4499.             msg = Regex.Replace(msg, @"\^[0-9a-zA-Z]", "");
  4500.  
  4501.             foreach (string name in admin_list)
  4502.             {
  4503.                 PlayerProfile pp = this.getPlayerProfile(name);
  4504.                 if (pp != null)
  4505.                 {
  4506.                     SendPlayerMessage(pp.name, msg);
  4507.                 }
  4508.             }
  4509.         }
  4510.  
  4511.  
  4512.         private void KickPlayerWithMessage(PlayerProfile player, string message)
  4513.         {
  4514.             if (player == null)
  4515.                 return;
  4516.  
  4517.             player.state = PlayerState.kicked;
  4518.             this.ExecuteCommand("procon.protected.send", "admin.kickPlayer", player.name, message);
  4519.         }
  4520.  
  4521.         private void inGameCommand(string cmd)
  4522.         {
  4523.             inGameCommand(getAdminList()[0], cmd);
  4524.         }
  4525.  
  4526.         private void inGameCommand(string sender, string cmd)
  4527.         {
  4528.  
  4529.  
  4530.             //Player commands
  4531.             Match adminMovePlayerMatch = Regex.Match(cmd, @"\s*[!@/]\s*move\s+([^ ]+)", RegexOptions.IgnoreCase);
  4532.             Match movePlayerMatch = Regex.Match(cmd, @"\s*[!@/]\s*move", RegexOptions.IgnoreCase);
  4533.  
  4534.  
  4535.  
  4536.  
  4537.             Match showPlayerRoundStatsMatch = Regex.Match(cmd, @"\s*[!@/]\s*show\s+round\s+stats\s+([^ ]+)", RegexOptions.IgnoreCase);
  4538.             Match showRoundStatsMatch = Regex.Match(cmd, @"\s*[!@/]\s*show\s+round\s+stats", RegexOptions.IgnoreCase);
  4539.             Match showIdlePlayersMatch = Regex.Match(cmd, @"\s*[!@/]\s*show\s+idle", RegexOptions.IgnoreCase);
  4540.             Match wlistInfoPlayerMatch = Regex.Match(cmd, @"\s*[!@/]\s*wlist_info\s+([^ ]+)", RegexOptions.IgnoreCase);
  4541.  
  4542.             Match stopBalancerMatch = Regex.Match(cmd, @"\s*[!@/]\s*stop\s+check", RegexOptions.IgnoreCase);
  4543.             Match startBalancerMatch = Regex.Match(cmd, @"\s*[!@/]\s*start\s+check", RegexOptions.IgnoreCase);
  4544.             Match balanceLiveMatch = Regex.Match(cmd, @"\s*[!@/]\s*balance\s+live", RegexOptions.IgnoreCase);
  4545.             Match balanceRoundMatch = Regex.Match(cmd, @"\s*[!@/]\s*balance\s+round", RegexOptions.IgnoreCase);
  4546.  
  4547.  
  4548.             //Setting/Getting variables
  4549.             Match setVarValueMatch = Regex.Match(cmd, @"\s*[!@/]\s*set\s+([^ ]+)\s+(.+)", RegexOptions.IgnoreCase);
  4550.             Match setVarValueEqMatch = Regex.Match(cmd, @"\s*[!@/]\s*set\s+([^ ]+)\s*=\s*(.+)", RegexOptions.IgnoreCase);
  4551.             Match setVarValueToMatch = Regex.Match(cmd, @"\s*[!@/]\s*set\s+([^ ]+)\s+to\s+(.+)", RegexOptions.IgnoreCase);
  4552.             Match setVarTrueMatch = Regex.Match(cmd, @"\s*[!@/]\s*set\s+([^ ]+)", RegexOptions.IgnoreCase);
  4553.             Match getVarValueMatch = Regex.Match(cmd, @"\s*[!@/]\s*get\s+([^ ]+)", RegexOptions.IgnoreCase);
  4554.             Match enableMatch = Regex.Match(cmd, @"\s*[!@/]\s*enable\s+(.+)", RegexOptions.IgnoreCase);
  4555.             Match disableMatch = Regex.Match(cmd, @"\s*[!@/]\s*disable\s+(.+)", RegexOptions.IgnoreCase);
  4556.  
  4557.             //Information
  4558.             Match pluginSettingsMatch = Regex.Match(cmd, @"\s*[!@/]\s*settings", RegexOptions.IgnoreCase);
  4559.  
  4560.  
  4561.             bool senderIsAdmin = isAdmin(sender);
  4562.  
  4563.  
  4564.             DateTime now = utc;
  4565.             if (showIdlePlayersMatch.Success && senderIsAdmin)
  4566.                 showIdlePlayers(sender);
  4567.             if (wlistInfoPlayerMatch.Success && senderIsAdmin)
  4568.                 wlistInfoPlayer(sender, wlistInfoPlayerMatch.Groups[1].Value);
  4569.             else if (startBalancerMatch.Success && senderIsAdmin)
  4570.                 startBalancerCmd(sender, now);
  4571.             else if (stopBalancerMatch.Success && senderIsAdmin)
  4572.                 stopBalancerCmd(sender, now);
  4573.             else if (showPlayerRoundStatsMatch.Success && senderIsAdmin)
  4574.                 showPlayerRoundStatsCmd(sender, showPlayerRoundStatsMatch.Groups[1].Value);
  4575.             else if (showRoundStatsMatch.Success && senderIsAdmin)
  4576.                 showPlayerRoundStatsCmd(sender, null);
  4577.             else if (balanceLiveMatch.Success && senderIsAdmin)
  4578.                 balanceLiveCmd(sender, now);
  4579.             else if (balanceRoundMatch.Success && senderIsAdmin)
  4580.                 balanceRoundCmd(sender, now);
  4581.             else if (adminMovePlayerMatch.Success && senderIsAdmin)
  4582.                 movePlayerCmd(sender, adminMovePlayerMatch.Groups[1].Value);
  4583.             else if (movePlayerMatch.Success)
  4584.                 movePlayerCmd(sender);
  4585.             else if (setVarValueEqMatch.Success && senderIsAdmin)
  4586.                 setVariableCmd(sender, setVarValueEqMatch.Groups[1].Value, setVarValueEqMatch.Groups[2].Value);
  4587.             else if (setVarValueToMatch.Success && senderIsAdmin)
  4588.                 setVariableCmd(sender, setVarValueToMatch.Groups[1].Value, setVarValueToMatch.Groups[2].Value);
  4589.             else if (setVarValueMatch.Success && senderIsAdmin)
  4590.                 setVariableCmd(sender, setVarValueMatch.Groups[1].Value, setVarValueMatch.Groups[2].Value);
  4591.             else if (setVarTrueMatch.Success && senderIsAdmin)
  4592.                 setVariableCmd(sender, setVarTrueMatch.Groups[1].Value, "1");
  4593.             else if (getVarValueMatch.Success && senderIsAdmin)
  4594.                 getVariableCmd(sender, getVarValueMatch.Groups[1].Value);
  4595.             else if (enableMatch.Success && senderIsAdmin)
  4596.                 enableVarGroupCmd(sender, enableMatch.Groups[1].Value);
  4597.             else if (disableMatch.Success && senderIsAdmin)
  4598.                 disableVarGroupCmd(sender, disableMatch.Groups[1].Value);
  4599.             else if (pluginSettingsMatch.Success && senderIsAdmin)
  4600.                 pluginSettingsCmd(sender);
  4601.         }
  4602.  
  4603.  
  4604.  
  4605.  
  4606.  
  4607.         private string state2strWHILE(PluginState state)
  4608.         {
  4609.             if (state.Equals(PluginState.balance))
  4610.             {
  4611.                 return "balancing";
  4612.             }
  4613.             else if (state.Equals(PluginState.check))
  4614.             {
  4615.                 return "checking";
  4616.             }
  4617.             else if (state.Equals(PluginState.warn))
  4618.             {
  4619.                 return "warning";
  4620.             }
  4621.             else if (state.Equals(PluginState.stop))
  4622.             {
  4623.                 return "stopped";
  4624.             }
  4625.             else if (state.Equals(PluginState.wait))
  4626.             {
  4627.                 return "waiting";
  4628.             }
  4629.  
  4630.             return "unknown state";
  4631.         }
  4632.  
  4633.  
  4634.  
  4635.         private void initializeBalancer()
  4636.         {
  4637.             getServerInfo();
  4638.             startStopState(utc);
  4639.         }
  4640.  
  4641.  
  4642.         private void movePlayerCmd(string sender)
  4643.         {
  4644.             if (teamsUnbalanced())
  4645.             {
  4646.                 SendConsoleMessage(sender, "Teams are un-balanced, cannot move to other team");
  4647.                 return;
  4648.             }
  4649.  
  4650.             movePlayerCmd(sender, null);
  4651.         }
  4652.  
  4653.         private void movePlayerCmd(string sender, string player)
  4654.         {
  4655.             /* player is moving himself */
  4656.             if (player == null)
  4657.                 player = sender;
  4658.  
  4659.             SendConsoleMessage(sender, "moving player " + player);
  4660.  
  4661.             PlayerProfile profile = getPlayerProfile(player);
  4662.  
  4663.             if (profile == null)
  4664.             {
  4665.                 SendConsoleMessage(sender, "cannot find profile for " + player);
  4666.                 return;
  4667.             }
  4668.  
  4669.             if (profile.getTeamId() == 0)
  4670.             {
  4671.                 SendConsoleMessage(sender, "cannot move " + player + " from neutral team");
  4672.                 return;
  4673.             }
  4674.  
  4675.             int opposite = (profile.getTeamId() == 1) ? 2 : 1;
  4676.             movePlayer(profile, opposite, 0, false, true);
  4677.         }
  4678.  
  4679.  
  4680.         private void startWaitSate(DateTime now)
  4681.         {
  4682.             startWaitSate(null, now);
  4683.         }
  4684.  
  4685.  
  4686.  
  4687.         private void startWarnState(DateTime now)
  4688.         {
  4689.             startWarnState(null, now);
  4690.         }
  4691.  
  4692.         private void startWarnState(string sender, DateTime now)
  4693.         {
  4694.             if (!isPluginChecking())
  4695.             {
  4696.                 SendConsoleMessage(sender, "plugin is in " + pluginState.ToString() + " state");
  4697.                 return;
  4698.             }
  4699.  
  4700.             pluginState = PluginState.warn;
  4701.             setStartTime(pluginState, now.AddSeconds(1));
  4702.  
  4703.             DebugWrite("^b" + pluginState + "^n state started " + getStartTime(pluginState).ToString(), 1);
  4704.         }
  4705.  
  4706.         private void startWaitSate(string sender, DateTime now)
  4707.         {
  4708.  
  4709.             if (!isPluginStopped())
  4710.             {
  4711.                 SendConsoleMessage(sender, "cannot start while balancer is in " + pluginState.ToString() + " state");
  4712.                 return;
  4713.             }
  4714.  
  4715.             if (sender != null)
  4716.                 setPluginVarValue("auto_start", "true");
  4717.  
  4718.  
  4719.             pluginState = PluginState.wait;
  4720.             setStartTime(pluginState, now.AddSeconds(1));
  4721.  
  4722.  
  4723.             SendConsoleMessage(sender, "^b" + pluginState + "^n state started " + getStartTime(pluginState).ToString());
  4724.         }
  4725.  
  4726.         private void startStopState(DateTime now)
  4727.         {
  4728.             startStopState(null, now);
  4729.         }
  4730.  
  4731.         private void startStopState(string sender, DateTime now)
  4732.         {
  4733.             virtual_mode = false;
  4734.             round_balancer = false;
  4735.             level_started = false;
  4736.             check_state_phase = 0;
  4737.  
  4738.             if (sender != null)
  4739.                 setPluginVarValue("auto_start", "false");
  4740.  
  4741.             pluginState = PluginState.stop;
  4742.             setStartTime(pluginState, now.AddSeconds(1));
  4743.  
  4744.             SendConsoleMessage(sender, "^b" + pluginState + "^n state started " + getStartTime(pluginState).ToString());
  4745.         }
  4746.  
  4747.  
  4748.         public void balanceLiveCmd(string sender, DateTime now)
  4749.         {
  4750.  
  4751.             balanceLive(now);
  4752.             restartWaitState(now);
  4753.         }
  4754.  
  4755.         public void balanceRoundCmd(string sender, DateTime now)
  4756.         {
  4757.             try
  4758.             {
  4759.                 balanceRound(1);
  4760.                 restartWaitState(utc);
  4761.                 resetPlayerStats();
  4762.             }
  4763.             catch (Exception e)
  4764.             {
  4765.                 dump_exception(e);
  4766.             }
  4767.  
  4768.         }
  4769.  
  4770.         private bool isPlayerIdle(PlayerProfile player)
  4771.         {
  4772.             int last_kill_time = getIntegerVarValue("last_kill_time");
  4773.             int last_death_time = getIntegerVarValue("last_death_time");
  4774.             int last_chat_time = getIntegerVarValue("last_chat_time");
  4775.             int last_spawn_time = getIntegerVarValue("last_spawn_time");
  4776.             int last_score_time = getIntegerVarValue("last_score_time");
  4777.  
  4778.            
  4779.             if (player.getLastKill() > last_kill_time &&
  4780.                 player.getLastDeath() > last_death_time &&
  4781.                 player.getLastChat() > last_chat_time &&
  4782.                 player.getLastSpawn() > last_spawn_time &&
  4783.                 player.getLastScore() > last_score_time)
  4784.                 return true;
  4785.  
  4786.             return false;
  4787.  
  4788.         }
  4789.  
  4790.         public void showIdlePlayers(string sender)
  4791.         {
  4792.             List<PlayerProfile> players_list = getPlayersProfile("");
  4793.  
  4794.             if (players_list.Count == 0)
  4795.                 return;
  4796.  
  4797.             SendConsoleMessage(sender, " == idle players (watching for last " + Math.Round(getRoundMinutes(), 2) + " minutes)  ==");
  4798.             foreach (PlayerProfile player in players_list)
  4799.                 if (isPlayerIdle(player))
  4800.                     SendConsoleMessage(sender, player + ": " + player.getIdleStatistics());
  4801.         }
  4802.  
  4803.  
  4804.         public void wlistInfoPlayer(string sender, string pname)
  4805.         {
  4806.             SendConsoleMessage(sender, " == White List Info for " + pname + "  ==");
  4807.             PlayerProfile player = getPlayerProfile(pname);
  4808.             if (player == null)
  4809.                 return;
  4810.  
  4811.             List<String> list_names =  new List<string>();
  4812.             list_names.Add("player_move_wlist");
  4813.             list_names.Add("clan_move_wlist");
  4814.             list_names.Add("player_safe_wlist");
  4815.             list_names.Add("clan_move_wlist");
  4816.             list_names.Add("player_safe_wlist");
  4817.             list_names.Add("clan_safe_wlist");
  4818.  
  4819.             foreach (String list in list_names)
  4820.             {
  4821.                 Boolean inlist = isPlayerInWhiteList(player, list);
  4822.                 SendConsoleMessage(sender, list + " " + inlist.ToString());
  4823.             }
  4824.  
  4825.         }
  4826.  
  4827.  
  4828.         public void showPlayerRoundStatsCmd(string sender, string player_name)
  4829.         {
  4830.             List<PlayerProfile> players_list;
  4831.             if (player_name == null)
  4832.                 players_list = getPlayersProfile("");
  4833.             else
  4834.                 players_list = getPlayersProfile(player_name);
  4835.  
  4836.  
  4837.             if (players_list.Count == 0)
  4838.                 return;
  4839.  
  4840.             int i = 1;
  4841.             SendConsoleMessage(sender, " == Round Statistics ( " + Math.Round(getRoundMinutes(), 2) + " minutes) ==");
  4842.             foreach (PlayerProfile player in players_list)
  4843.             {
  4844.                 SendConsoleMessage(sender, i + ". " +player + ": " + player.getRoundStatistics());
  4845.                 i++;
  4846.             }
  4847.         }
  4848.  
  4849.         private void startBalancerCmd(string sender, DateTime now)
  4850.         {
  4851.             setBooleanVarValue("balance_live", true);
  4852.             startWaitSate(now);
  4853.         }
  4854.  
  4855.         private void stopBalancerCmd(string sender, DateTime now)
  4856.         {
  4857.             setBooleanVarValue("balance_live", false);
  4858.             startStopState(now);
  4859.         }
  4860.  
  4861.         private void restartWaitState(DateTime now)
  4862.         {
  4863.             pluginState = PluginState.wait;
  4864.             setStartTime(pluginState, now.AddSeconds(1));
  4865.             DebugWrite("^b" + pluginState.ToString() + "^n state re-started " + getStartTime(pluginState).ToString() + "^0", 1);
  4866.         }
  4867.  
  4868.  
  4869.  
  4870.         private void genericSayAnnounce(List<string> messages)
  4871.         {
  4872.             if (messages.Count == 0)
  4873.                 return;
  4874.  
  4875.             int remain_time = getRemainingTime(utc, pluginState);
  4876.  
  4877.             for (int i = 0; i < messages.Count; i++)
  4878.             {
  4879.                 string msg = messages[i];
  4880.                 msg = msg.Replace("%time%", remain_time.ToString());
  4881.                 SendGlobalMessage(msg);
  4882.             }
  4883.  
  4884.         }
  4885.  
  4886.  
  4887.  
  4888.         private void warnAnnounce(int display_time)
  4889.         {
  4890.             if (!isPluginWarning())
  4891.                 return;
  4892.  
  4893.             DebugWrite("sending ^b" + pluginState.ToString() + "^n announcement", 1);
  4894.  
  4895.             List<string> msg = new List<string>();
  4896.             msg.Add("Teams are unbalanced");
  4897.             msg.Add("Autobalancer starts in %time% secs");
  4898.  
  4899.             if (getBooleanVarValue("warn_say"))
  4900.                 genericSayAnnounce(msg);
  4901.         }
  4902.  
  4903.  
  4904.         private void warnCountdown()
  4905.         {
  4906.             if (!isPluginWarning())
  4907.                 return;
  4908.  
  4909.             DebugWrite("sending ^b" + pluginState.ToString() + "^n countdown", 1);
  4910.  
  4911.             int remain_time = getRemainingTime(utc, PluginState.warn);
  4912.             string msg = "Autobalancer starts in " + remain_time.ToString() + "!";
  4913.  
  4914.             if (getBooleanVarValue("warn_say"))
  4915.                 SendGlobalMessage(msg);
  4916.         }
  4917.  
  4918.         private void enableVarGroupCmd(string sender, string group)
  4919.         {
  4920.             if (group.CompareTo("plugin") == 0)
  4921.             {
  4922.                 ConsoleWrite("Disabling plugin");
  4923.                 this.ExecuteCommand("procon.plugin.enable", "InsaneBalancer", "false");
  4924.             }
  4925.             enablePluginVarGroup(sender, group);
  4926.         }
  4927.  
  4928.         private void disableVarGroupCmd(string sender, string group)
  4929.         {
  4930.             if (group.CompareTo("plugin") == 0)
  4931.             {
  4932.                 ConsoleWrite("Enabling plugin");
  4933.                 this.ExecuteCommand("procon.plugin.enable", "InsaneBalancer", "true");
  4934.             }
  4935.  
  4936.             disablePluginVarGroup(sender, group);
  4937.         }
  4938.  
  4939.         private bool setPluginVarGroup(string sender, string group, string val)
  4940.         {
  4941.             String msg = "";
  4942.             if (group == null)
  4943.             {
  4944.                 msg = "no variables to enable";
  4945.                 ConsoleWrite(msg);
  4946.                 SendPlayerMessage(sender, msg);
  4947.                 return false;
  4948.             }
  4949.  
  4950.  
  4951.             group = group.Replace(";", ",");
  4952.             List<string> vars = new List<string>(Regex.Split(group, @"\s*,\s*", RegexOptions.IgnoreCase));
  4953.             foreach (string var in vars)
  4954.             {
  4955.                 if (setPluginVarValue(sender, var, val))
  4956.                 {
  4957.                     msg = var + " set to \"" + val + "\"";
  4958.                     SendPlayerMessage(sender, msg);
  4959.                 }
  4960.  
  4961.             }
  4962.             return true;
  4963.         }
  4964.  
  4965.         private bool enablePluginVarGroup(string sender, string group)
  4966.         {
  4967.             //search for all variables matching
  4968.             List<string> vars = getVariableNames(group);
  4969.             String msg = "";
  4970.             if (vars.Count == 0)
  4971.             {
  4972.                 msg = "no variables match \"" + group + "\"";
  4973.                 ConsoleWrite(msg);
  4974.                 SendPlayerMessage(sender, msg);
  4975.                 return false;
  4976.             }
  4977.  
  4978.             return setPluginVarGroup(sender, String.Join(",", vars.ToArray()), "true");
  4979.         }
  4980.  
  4981.         private List<string> getVariableNames(string group)
  4982.         {
  4983.             List<string> names = new List<string>();
  4984.             List<string> list = new List<string>(Regex.Split(group, @"\s*,\s*"));
  4985.             List<string> vars = getPluginVars();
  4986.             foreach (string search in list)
  4987.             {
  4988.                 foreach (string var in vars)
  4989.                 {
  4990.                     if (var.Contains(search))
  4991.                         if (!names.Contains(var))
  4992.                             names.Add(var);
  4993.                 }
  4994.             }
  4995.  
  4996.             return names;
  4997.         }
  4998.  
  4999.         private bool disablePluginVarGroup(string sender, string group)
  5000.         {
  5001.             //search for all variables matching
  5002.             List<string> vars = getVariableNames(group);
  5003.  
  5004.             if (vars.Count == 0)
  5005.             {
  5006.                 SendConsoleMessage(sender, "no variables match \"" + group + "\"");
  5007.                 return false;
  5008.             }
  5009.             return setPluginVarGroup(sender, String.Join(",", vars.ToArray()), "false");
  5010.         }
  5011.  
  5012.         private void getVariableCmd(string sender, string var)
  5013.         {
  5014.             string val = getPluginVarValue(sender, var);
  5015.  
  5016.             if (var.Equals("pass"))
  5017.                 val = Regex.Replace(val, @".", "*");
  5018.  
  5019.             String msg = var + " = " + val;
  5020.  
  5021.             ConsoleWrite(msg);
  5022.             SendPlayerMessage(sender, msg);
  5023.         }
  5024.  
  5025.  
  5026.  
  5027.  
  5028.         private void setVariableCmd(string sender, string var, string val)
  5029.         {
  5030.  
  5031.             if (setPluginVarValue(sender, var, val))
  5032.             {
  5033.                 SendConsoleMessage(sender, var + " set to \"" + val + "\"");
  5034.             }
  5035.         }
  5036.  
  5037.         private void pluginSettingsCmd(string sender)
  5038.         {
  5039.             SendConsoleMessage(sender, " == Insane Balancer Settings == ");
  5040.             foreach (string var in getPluginVars())
  5041.             {
  5042.                 SendConsoleMessage(sender, var + " = " + getPluginVarValue(sender, var));
  5043.             }
  5044.         }
  5045.  
  5046.  
  5047.         public bool stringValidator(string var, string value)
  5048.         {
  5049.             if (var.CompareTo("round_sort") == 0)
  5050.             {
  5051.                 if (!strAssertSort(value))
  5052.                     return false;
  5053.             }
  5054.             if (var.CompareTo("live_sort") == 0)
  5055.             {
  5056.                 if (!strAssertSort(value))
  5057.                     return false;
  5058.             }
  5059.             return true;
  5060.         }
  5061.  
  5062.         public bool commandValidator(string var, string value)
  5063.         {
  5064.  
  5065.             inGameCommand(value);
  5066.             return false;
  5067.         }
  5068.  
  5069.  
  5070.         public List<String> getAllowedSorts()
  5071.         {
  5072.             List<string> sort_methods = new List<string>();
  5073.  
  5074.  
  5075.             sort_methods.Add("kdr_asc_round");
  5076.             sort_methods.Add("kdr_desc_round");
  5077.             sort_methods.Add("spm_asc_round");
  5078.             sort_methods.Add("spm_desc_round");
  5079.             sort_methods.Add("kpm_asc_round");
  5080.             sort_methods.Add("kpm_desc_round");
  5081.             sort_methods.Add("score_asc_round");
  5082.             sort_methods.Add("score_desc_round");
  5083.             sort_methods.Add("time_asc_round");
  5084.             sort_methods.Add("time_desc_round");
  5085.  
  5086.             return sort_methods;
  5087.         }
  5088.  
  5089.  
  5090.         public bool strAssertSort(string value)
  5091.         {
  5092.             if (value == null)
  5093.                 return false;
  5094.  
  5095.  
  5096.             List<String> sort_methods = getAllowedSorts();
  5097.  
  5098.             if (!sort_methods.Contains(value))
  5099.             {
  5100.                 SendConsoleMessage("^1^bERROR^0^n: ^b" + value + "^n is not a valid sort method ^0");
  5101.                 SendConsoleMessage("valid sort methods are: ^b" + String.Join("^0,^b ", sort_methods.ToArray()) + "^0");
  5102.                 return false;
  5103.             }
  5104.             return true;
  5105.         }
  5106.  
  5107.         public bool booleanValidator(string var, bool value)
  5108.         {
  5109.             return true;
  5110.         }
  5111.  
  5112.  
  5113.         bool boolAssertNE(string var, bool value, string cmp)
  5114.         {
  5115.             bool cmp_value = getBooleanVarValue(cmp);
  5116.  
  5117.             if (!(value != cmp_value))
  5118.             {
  5119.                 ConsoleWrite("^1^bERROR^0^n:  cannot set ^b" + var + "^n to ^b" + value.ToString() + "^n while ^b" + cmp + "^n is set to ^b" + cmp_value.ToString() + "^n^0");
  5120.                 return false;
  5121.             }
  5122.             return true;
  5123.         }
  5124.  
  5125.         public bool integerValidator(string var, int value)
  5126.         {
  5127.  
  5128.             if (var.CompareTo("warn_msg_interval_time") == 0)
  5129.             {
  5130.                 if (!intAssertGTE(var, value, 0) ||
  5131.                     !intAssertLTE(var, value, "warn_msg_total_time"))
  5132.                     return false;
  5133.             }
  5134.  
  5135.             if (var.CompareTo("warn_msg_countdown_time") == 0)
  5136.             {
  5137.                 if (!intAssertGTE(var, value, 0) ||
  5138.                     !intAssertLTE(var, value, "warn_msg_total_time"))
  5139.                     return false;
  5140.             }
  5141.  
  5142.             if (var.CompareTo("warn_msg_total_time") == 0)
  5143.             {
  5144.                 if (!intAssertGTE(var, value, 0) ||
  5145.                     !intAssertGTE(var, value, "warn_msg_interval_time") ||
  5146.                     !intAssertGTE(var, value, "warn_msg_countdown_time"))
  5147.                     return false;
  5148.             }
  5149.  
  5150.             if (var.CompareTo("warn_msg_display_time") == 0)
  5151.             {
  5152.                 if (!intAssertGTE(var, value, 0) ||
  5153.                     !intAssertLTE(var, value, "warn_msg_total_time"))
  5154.                     return false;
  5155.             }
  5156.  
  5157.             if (var.CompareTo("balance_threshold") == 0)
  5158.             {
  5159.                 if (!intAssertGT(var, value, 0))
  5160.                     return false;
  5161.             }
  5162.  
  5163.             if (var.CompareTo("round_interval") == 0)
  5164.             {
  5165.  
  5166.                 if (!intAssertGT(var, value, 0))
  5167.                     return false;
  5168.  
  5169.                 if (serverInfo == null)
  5170.                     return true;
  5171.  
  5172.                 if (value > serverInfo.TotalRounds)
  5173.                 {
  5174.                     SendConsoleMessage("^1^bERROR^0^n: ^b" + var + "(" + value + ")^n must be less than or equal than the total number of ^brounds(" + serverInfo.TotalRounds + ")^n per ^bmap(" + serverInfo.Map.ToLower() + ")^n^0");
  5175.                     return false;
  5176.                 }
  5177.             }
  5178.  
  5179.             if (var.CompareTo("live_interval_time") == 0)
  5180.             {
  5181.                 if (!intAssertGT(var, value, 0))
  5182.                     return false;
  5183.             }
  5184.  
  5185.             if (var.CompareTo("debug_level") == 0)
  5186.             {
  5187.                 if (!intAssertGTE(var, value, 0))
  5188.                     return false;
  5189.             }
  5190.  
  5191.             return true;
  5192.         }
  5193.  
  5194.  
  5195.         private bool intAssertLT(string var, int value, int max_value)
  5196.         {
  5197.             if (!(value < max_value))
  5198.             {
  5199.                 SendConsoleMessage("^1^bERROR^0^n: b" + var + "(" + value + ")^n must be less than  ^b" + max_value + "^n^0");
  5200.                 return false;
  5201.             }
  5202.  
  5203.             return true;
  5204.         }
  5205.  
  5206.  
  5207.         private bool intAssertLTE(string var, int value, int max_value)
  5208.         {
  5209.             if (!(value <= max_value))
  5210.             {
  5211.                 SendConsoleMessage("^1^bERROR^0^n: ^b" + var + "(" + value + ")^n must be less than or equal to ^b" + max_value + "^n^0");
  5212.                 return false;
  5213.             }
  5214.  
  5215.             return true;
  5216.         }
  5217.  
  5218.  
  5219.         private bool intAssertGT(string var, int value, int min_value)
  5220.         {
  5221.             if (!(value > min_value))
  5222.             {
  5223.                 SendConsoleMessage("^1^bERROR^0^n: ^b" + var + "(" + value + ")^n must be greater than  ^b" + min_value + "^n^0");
  5224.                 return false;
  5225.             }
  5226.  
  5227.             return true;
  5228.         }
  5229.  
  5230.  
  5231.         private bool intAssertGTE(string var, int value, int min_value)
  5232.         {
  5233.             if (!(value >= min_value))
  5234.             {
  5235.                 SendConsoleMessage("^1^bERROR^0^n: ^b" + var + "(" + value + ")^n must be greater than or equal to ^b" + min_value + "^n^0");
  5236.                 return false;
  5237.             }
  5238.  
  5239.             return true;
  5240.         }
  5241.  
  5242.         private bool intAssertGTE(string var1, int var1_value, string var2)
  5243.         {
  5244.             int var2_value = getIntegerVarValue(var2);
  5245.  
  5246.             if (!(var1_value >= var2_value))
  5247.             {
  5248.  
  5249.                 SendConsoleMessage("^1^bERROR^0^n: ^b" + var1 + "(" + var1_value + ")^n must be greater than or equal to the value of ^b" + var2 + "(" + var2_value + ")^n");
  5250.  
  5251.                 return false;
  5252.             }
  5253.  
  5254.             return true;
  5255.         }
  5256.  
  5257.  
  5258.         private bool intAssertLTE(string var1, int var1_value, string var2)
  5259.         {
  5260.             int var2_value = getIntegerVarValue(var2);
  5261.  
  5262.  
  5263.             if (!(var1_value <= var2_value))
  5264.             {
  5265.                 SendConsoleMessage("^1^bERROR^0^n: ^b" + var1 + "(" + var1_value + ")^n must be less than or equal to the value of ^b" + var2 + "(" + var2_value + ")^n");
  5266.                 return false;
  5267.             }
  5268.  
  5269.             return true;
  5270.         }
  5271.  
  5272.  
  5273.         private bool setPluginVarValue(string var, string val)
  5274.         {
  5275.             return setPluginVarValue(null, var, val);
  5276.         }
  5277.  
  5278.         private bool setPluginVarValue(string sender, string var, string val)
  5279.         {
  5280.             if (var == null || val == null)
  5281.                 return false;
  5282.  
  5283.             if (!getPluginVars().Contains(var))
  5284.             {
  5285.                 SendConsoleMessage(sender, "Insane Balancer: unknown variable \"" + var + "\"");
  5286.                 return false;
  5287.             }
  5288.  
  5289.             /* Parse Boolean Values */
  5290.             bool booleanValue = false;
  5291.             bool isBooleanValue = true;
  5292.             if (Regex.Match(val, @"\s*(1|true|yes)\s*", RegexOptions.IgnoreCase).Success)
  5293.                 booleanValue = true;
  5294.             else if (Regex.Match(val, @"\s*(0|false|no)\s*", RegexOptions.IgnoreCase).Success)
  5295.                 booleanValue = false;
  5296.             else
  5297.                 isBooleanValue = false;
  5298.  
  5299.  
  5300.             /* Parse Integer Values */
  5301.             int integerValue = 0;
  5302.             //bool isIntegerValue = int.TryParse(val, out integerValue) && integerValue >= 0;
  5303.             bool isIntegerValue = int.TryParse(val, out integerValue);
  5304.  
  5305.             /* Parse Float Values */
  5306.             float floatValue = 0F;
  5307.             bool isFloatValue = float.TryParse(val, out floatValue) && floatValue >= 0F;
  5308.  
  5309.             /* Parse String List */
  5310.             List<string> stringListValue = new List<string>(Regex.Split(val.Replace(";", ",").Replace("|", ","), @"\s*,\s*"));
  5311.             bool isStringList = true;
  5312.  
  5313.             /* Parse String var */
  5314.             string stringValue = val;
  5315.             bool isStringValue = (val != null);
  5316.  
  5317.  
  5318.             if (isBooleanVar(var))
  5319.             {
  5320.                 if (!isBooleanValue)
  5321.                 {
  5322.                     SendConsoleMessage(sender, "\"" + val + "\" is invalid for " + var);
  5323.                     return false;
  5324.                 }
  5325.                 setBooleanVarValue(var, booleanValue);
  5326.                 return true;
  5327.             }
  5328.             else if (isIntegerVar(var))
  5329.             {
  5330.                 if (!isIntegerValue)
  5331.                 {
  5332.                     SendConsoleMessage(sender, "\"" + val + "\" is invalid for " + var);
  5333.                     return false;
  5334.                 }
  5335.  
  5336.                 setIntegerVarValue(var, integerValue);
  5337.                 return true;
  5338.             }
  5339.             else if (isFloatVar(var))
  5340.             {
  5341.                 if (!isFloatValue)
  5342.                 {
  5343.                     SendConsoleMessage(sender, "\"" + val + "\" is invalid for " + var);
  5344.                     return false;
  5345.                 }
  5346.  
  5347.                 setFloatVarValue(var, floatValue);
  5348.                 return true;
  5349.             }
  5350.             else if (isStringListVar(var))
  5351.             {
  5352.                 if (!isStringList)
  5353.                 {
  5354.                     SendConsoleMessage(sender, "\"" + val + "\"  is invalid for " + var);
  5355.                     return false;
  5356.                 }
  5357.  
  5358.                 setStringListVarValue(var, stringListValue);
  5359.                 return true;
  5360.             }
  5361.             else if (isStringVar(var))
  5362.             {
  5363.                 if (!isStringValue)
  5364.                 {
  5365.                     SendConsoleMessage(sender, "invalid value for " + var);
  5366.                     return false;
  5367.                 }
  5368.  
  5369.                 setStringVarValue(var, stringValue);
  5370.                 return true;
  5371.             }
  5372.             else
  5373.             {
  5374.                 SendConsoleMessage(sender, "Insane Balancer: unknown variable \"" + var + "\"");
  5375.                 return false;
  5376.             }
  5377.  
  5378.         }
  5379.  
  5380.         private bool isIntegerVar(string var)
  5381.         {
  5382.             return this.integerVariables.ContainsKey(var);
  5383.         }
  5384.  
  5385.         private int getIntegerVarValue(string var)
  5386.         {
  5387.             if (!isIntegerVar(var))
  5388.             {
  5389.                 SendConsoleMessage("unknown variable \"" + var + "\"");
  5390.                 return -1;
  5391.             }
  5392.  
  5393.             return this.integerVariables[var];
  5394.         }
  5395.  
  5396.         private bool setIntegerVarValue(string var, int val)
  5397.         {
  5398.             if (!isIntegerVar(var))
  5399.             {
  5400.                 SendConsoleMessage("unknown variable \"" + var + "\"");
  5401.                 return false;
  5402.             }
  5403.  
  5404.             if (hasIntegerValidator(var))
  5405.             {
  5406.                 integerVariableValidator validator = integerVarValidators[var];
  5407.                 if (validator(var, val) == false)
  5408.                     return false;
  5409.             }
  5410.  
  5411.             this.integerVariables[var] = val;
  5412.             return true;
  5413.         }
  5414.  
  5415.         private bool hasBooleanValidator(string var)
  5416.         {
  5417.             return booleanVarValidators.ContainsKey(var);
  5418.         }
  5419.  
  5420.         private bool hasIntegerValidator(string var)
  5421.         {
  5422.             return integerVarValidators.ContainsKey(var);
  5423.         }
  5424.  
  5425.         private bool hasStringValidator(string var)
  5426.         {
  5427.             return stringVarValidators.ContainsKey(var);
  5428.         }
  5429.  
  5430.         private bool isStringVar(string var)
  5431.         {
  5432.             return this.stringVariables.ContainsKey(var);
  5433.         }
  5434.  
  5435.  
  5436.         private string getStringVarValue(string var)
  5437.         {
  5438.             if (!isStringVar(var))
  5439.             {
  5440.                 SendConsoleMessage("unknown variable \"" + var + "\"");
  5441.                 return "";
  5442.             }
  5443.  
  5444.             return this.stringVariables[var];
  5445.         }
  5446.  
  5447.         private bool setStringVarValue(string var, string val)
  5448.         {
  5449.             if (!isStringVar(var))
  5450.             {
  5451.                 SendConsoleMessage("unknown variable \"" + var + "\"");
  5452.                 return false;
  5453.             }
  5454.  
  5455.  
  5456.             if (hasStringValidator(var))
  5457.             {
  5458.                 stringVariableValidator validator = stringVarValidators[var];
  5459.                 if (validator(var, val) == false)
  5460.                     return false;
  5461.             }
  5462.  
  5463.  
  5464.             string oldval = this.stringVariables[var];
  5465.             this.stringVariables[var] = val;
  5466.  
  5467.             return true;
  5468.         }
  5469.  
  5470.  
  5471.  
  5472.  
  5473.         private bool isStringListVar(string var)
  5474.         {
  5475.             return this.stringListVariables.ContainsKey(var);
  5476.         }
  5477.  
  5478.         private List<string> getStringListVarValue(string var)
  5479.         {
  5480.             if (!isStringListVar(var))
  5481.             {
  5482.                 SendConsoleMessage("unknown variable \"" + var + "\"");
  5483.                 return new List<string>();
  5484.             }
  5485.  
  5486.             string[] out_list = Regex.Split(this.stringListVariables[var].Replace(";", ",").Replace("|", ","), @"\s*,\s*");
  5487.             return new List<string>(out_list);
  5488.         }
  5489.  
  5490.         private bool setStringListVarValue(string var, List<string> val)
  5491.         {
  5492.             if (!isStringListVar(var))
  5493.             {
  5494.                 SendConsoleMessage("unknown variable \"" + var + "\"");
  5495.                 return false;
  5496.             }
  5497.  
  5498.             List<string> cleanList = new List<string>();
  5499.             foreach (string item in val)
  5500.                 if (Regex.Match(item, @"^\s*$").Success)
  5501.                     continue;
  5502.                 else
  5503.                     cleanList.Add(item);
  5504.  
  5505.             //this.stringListVariables[var] = val;
  5506.             this.stringListVariables[var] = String.Join("|", cleanList.ToArray());
  5507.             return true;
  5508.         }
  5509.  
  5510.  
  5511.         private bool isFloatVar(string var)
  5512.         {
  5513.             return this.floatVariables.ContainsKey(var);
  5514.         }
  5515.  
  5516.         private float getFloatVarValue(string var)
  5517.         {
  5518.             if (!isFloatVar(var))
  5519.             {
  5520.                 SendConsoleMessage("unknown variable \"" + var + "\"");
  5521.                 return -1F;
  5522.             }
  5523.  
  5524.             return this.floatVariables[var];
  5525.         }
  5526.  
  5527.         private bool setFloatVarValue(string var, float val)
  5528.         {
  5529.             if (!isFloatVar(var))
  5530.             {
  5531.                 SendConsoleMessage("unknown variable \"" + var + "\"");
  5532.                 return false;
  5533.             }
  5534.  
  5535.             this.floatVariables[var] = val;
  5536.             return true;
  5537.         }
  5538.  
  5539.  
  5540.         private bool isBooleanVar(string var)
  5541.         {
  5542.             return this.booleanVariables.ContainsKey(var);
  5543.         }
  5544.  
  5545.         private bool getBooleanVarValue(string var)
  5546.         {
  5547.             if (!isBooleanVar(var))
  5548.             {
  5549.                 SendConsoleMessage("unknown variable \"" + var + "\"");
  5550.                 return false;
  5551.             }
  5552.  
  5553.             return this.booleanVariables[var];
  5554.         }
  5555.  
  5556.         private bool setBooleanVarValue(string var, bool val)
  5557.         {
  5558.             if (!isBooleanVar(var))
  5559.             {
  5560.                 SendConsoleMessage("unknown variable \"" + var + "\"");
  5561.                 return false;
  5562.             }
  5563.  
  5564.             if (hasBooleanValidator(var))
  5565.             {
  5566.                 booleanVariableValidator validator = booleanVarValidators[var];
  5567.                 if (validator(var, val) == false)
  5568.                     return false;
  5569.             }
  5570.  
  5571.             this.booleanVariables[var] = val;
  5572.             return true;
  5573.         }
  5574.  
  5575.  
  5576.         private string getPluginVarValue(string var)
  5577.         {
  5578.             return getPluginVarValue(null, var);
  5579.         }
  5580.  
  5581.         private string getPluginVarValue(string sender, string var)
  5582.         {
  5583.             if (!getPluginVars().Contains(var))
  5584.             {
  5585.                 SendConsoleMessage(sender, "Insane Balancer: unknown variable \"" + var + "\"");
  5586.                 return "";
  5587.             }
  5588.  
  5589.             if (isBooleanVar(var))
  5590.             {
  5591.                 return getBooleanVarValue(var).ToString();
  5592.             }
  5593.             else if (isIntegerVar(var))
  5594.             {
  5595.                 return getIntegerVarValue(var).ToString();
  5596.             }
  5597.             else if (isFloatVar(var))
  5598.             {
  5599.                 return getFloatVarValue(var).ToString();
  5600.             }
  5601.             else if (isStringListVar(var))
  5602.             {
  5603.                 string lst = list2string(getStringListVarValue(var), "");
  5604.                 return lst;
  5605.             }
  5606.             else if (isStringVar(var))
  5607.             {
  5608.                 return getStringVarValue(var);
  5609.             }
  5610.             else
  5611.             {
  5612.                 SendConsoleMessage(sender, "Insane Balancer: unknown variable \"" + var + "\"");
  5613.                 return "";
  5614.             }
  5615.         }
  5616.  
  5617.         private List<string> getPluginVars()
  5618.         {
  5619.             return getPluginVars(false);
  5620.         }
  5621.  
  5622.         private List<string> getPluginVars(bool hide)
  5623.         {
  5624.             List<string> vars = new List<string>();
  5625.  
  5626.             vars.AddRange(getIntegerPluginVars());
  5627.             vars.AddRange(getBooleanPluginVars());
  5628.             vars.AddRange(getStringListPluginVars());
  5629.             vars.AddRange(getFloatPluginVars());
  5630.             vars.AddRange(getStringPluginVars());
  5631.  
  5632.             if (hide && !getBooleanVarValue("advanced_mode"))
  5633.             {
  5634.                 foreach (string hidden_var in hiddenVariables)
  5635.                     vars.Remove(hidden_var);
  5636.             }
  5637.  
  5638.             return vars;
  5639.         }
  5640.  
  5641.  
  5642.         private List<string> getStringPluginVars()
  5643.         {
  5644.             return new List<string>(this.stringVariables.Keys);
  5645.         }
  5646.  
  5647.  
  5648.         private List<string> getStringListPluginVars()
  5649.         {
  5650.             return new List<string>(this.stringListVariables.Keys);
  5651.         }
  5652.  
  5653.  
  5654.         private List<string> getIntegerPluginVars()
  5655.         {
  5656.             return new List<string>(this.integerVariables.Keys);
  5657.         }
  5658.  
  5659.         private List<string> getFloatPluginVars()
  5660.         {
  5661.             return new List<string>(this.floatVariables.Keys);
  5662.         }
  5663.  
  5664.         private List<string> getBooleanPluginVars()
  5665.         {
  5666.             return new List<string>(this.booleanVariables.Keys);
  5667.         }
  5668.  
  5669.         public string playerstate2stringED(PlayerState state)
  5670.         {
  5671.             switch (state)
  5672.             {
  5673.                 case PlayerState.alive:
  5674.                     return "is alive";
  5675.                 case PlayerState.dead:
  5676.                     return "is dead";
  5677.                 case PlayerState.kicked:
  5678.                     return "was kicked";
  5679.                 case PlayerState.left:
  5680.                     return "left the game";
  5681.                 case PlayerState.limbo:
  5682.                     return "is in limbo";
  5683.                 default:
  5684.                     return "(%player_state%)";
  5685.             }
  5686.  
  5687.         }
  5688.  
  5689.  
  5690.         public string list2string(List<string> list, string glue)
  5691.         {
  5692.  
  5693.             if (list == null || list.Count == 0)
  5694.                 return "";
  5695.             else if (list.Count == 1)
  5696.                 return list[0];
  5697.  
  5698.             string last = list[list.Count - 1];
  5699.             list.RemoveAt(list.Count - 1);
  5700.  
  5701.             string str = "";
  5702.             foreach (string item in list)
  5703.                 str += item + ", ";
  5704.  
  5705.             return str + glue + last;
  5706.         }
  5707.  
  5708.         public string list2string(List<string> list)
  5709.         {
  5710.             return list2string(list, "and ");
  5711.         }
  5712.  
  5713.  
  5714.         private List<string> getAdminList()
  5715.         {
  5716.             return getStringListVarValue("admin_list");
  5717.         }
  5718.  
  5719.         private bool isAdmin(string soldier)
  5720.         {
  5721.             List<string> admin_list = getAdminList();
  5722.             return admin_list.Contains(soldier);
  5723.         }
  5724.  
  5725.  
  5726.         private PlayerProfile getPlayerProfile(CPlayerInfo info)
  5727.         {
  5728.             return getPlayerProfile(info.SoldierName);
  5729.         }
  5730.  
  5731.  
  5732.         private List<PlayerProfile> getPlayersProfile(string name)
  5733.         {
  5734.  
  5735.             List<PlayerProfile> profiles = new List<PlayerProfile>();
  5736.             foreach (KeyValuePair<string, PlayerProfile> pair in this.players)
  5737.             {
  5738.  
  5739.                 if (pair.Value.info == null || pair.Value.info.TeamID < 0 ||
  5740.                     pair.Value.wasKicked() || pair.Value.leftGame())
  5741.                     continue;
  5742.  
  5743.                 if (name.Equals(""))
  5744.                     profiles.Add(pair.Value);
  5745.                 else if (pair.Key.ToLower().Contains(name.ToLower()))
  5746.                     profiles.Add(pair.Value);
  5747.             }
  5748.  
  5749.  
  5750.             return profiles;
  5751.         }
  5752.  
  5753.         private PlayerProfile getPlayerProfile(string name)
  5754.         {
  5755.             PlayerProfile pp;
  5756.             this.players.TryGetValue(name, out pp);
  5757.             return pp;
  5758.         }
  5759.  
  5760.  
  5761.         public override void OnPunkbusterPlayerInfo(CPunkbusterInfo cpbiPlayer)
  5762.         {
  5763.  
  5764.             if (cpbiPlayer == null)
  5765.                 return;
  5766.  
  5767.             battleLogConnect();
  5768.             if (this.players.ContainsKey(cpbiPlayer.SoldierName))
  5769.                 this.players[cpbiPlayer.SoldierName].pbinfo = cpbiPlayer;
  5770.             else
  5771.                 this.players.Add(cpbiPlayer.SoldierName, new PlayerProfile(this, cpbiPlayer));
  5772.  
  5773.         }
  5774.  
  5775.         public void dump_exception(Exception e)
  5776.         {
  5777.             ConsoleWrite("^1^bEXCEPTION^0^n: " + e.TargetSite + ": " + e.Message);
  5778.             try
  5779.             {
  5780.                 // Create a temporary file
  5781.                 string path = Path.GetRandomFileName() + ".dump";
  5782.  
  5783.  
  5784.                 ConsoleWrite("^1Extra information dumped in file " + path);
  5785.                 using (FileStream fs = File.Open(path, FileMode.OpenOrCreate))
  5786.                 {
  5787.                     Byte[] info = new UTF8Encoding(true).GetBytes(e.TargetSite + ": " + e.Message + "\n" + e.StackTrace + "\n");
  5788.                     fs.Write(info, 0, info.Length);
  5789.                 }
  5790.  
  5791.             }
  5792.             catch (Exception ex)
  5793.             {
  5794.                 ConsoleWrite("^1^bWARNING^0^n: Unable to dump extra exception information.");
  5795.                 ConsoleWrite("^1^bEXCEPTION^0^n:  " + ex.TargetSite + ": " + ex.Message);
  5796.  
  5797.             }
  5798.         }
  5799.  
  5800.         public override void OnListPlayers(List<CPlayerInfo> lstPlayers, CPlayerSubset cpsSubset)
  5801.         {
  5802.             List<String> players_left = new List<string>();
  5803.        
  5804.             foreach (CPlayerInfo cpiPlayer in lstPlayers)
  5805.                 if (this.players.ContainsKey(cpiPlayer.SoldierName))
  5806.                     this.players[cpiPlayer.SoldierName].updateInfo(cpiPlayer);
  5807.  
  5808.  
  5809.             /* make a list of players that are not in the given list */
  5810.             foreach(KeyValuePair<String, PlayerProfile> pair in this.players)
  5811.             {
  5812.                 bool found =  false;
  5813.                 foreach (CPlayerInfo cpi in lstPlayers)
  5814.                     if (pair.Key.Equals(cpi.SoldierName))
  5815.                     {
  5816.                         found = true;
  5817.                         break;
  5818.                     }
  5819.  
  5820.                 if (!found)
  5821.                     players_left.Add(pair.Key);
  5822.             }
  5823.  
  5824.             foreach (String pname in players_left)
  5825.                 if (this.players.ContainsKey(pname))
  5826.                     this.players.Remove(pname);
  5827.  
  5828.  
  5829.             /* fail safe to get the maximum number of players in server */
  5830.             if (lstPlayers.Count > max_player_count)
  5831.                 max_player_count = lstPlayers.Count;
  5832.  
  5833.  
  5834.             if (check_state_phase == 1)
  5835.                 startCheckState(utc);
  5836.         }
  5837.  
  5838.     }
  5839. }
  5840.  
  5841.  
  5842.  
  5843.  
Add Comment
Please, Sign In to add comment