public static void CreateFleetAt(string FleetUID, Empire Owner, Vector2 Position)
        {
            FileInfo theFleetFI;

            if (GlobalStats.ActiveMod != null && Directory.Exists(string.Concat(Ship_Game.ResourceManager.WhichModPath, "/FleetDesigns")) && File.Exists(string.Concat(Ship_Game.ResourceManager.WhichModPath, "/FleetDesigns/", FleetUID, ".xml")))
            {
                theFleetFI = new FileInfo(string.Concat(Ship_Game.ResourceManager.WhichModPath, "/FleetDesigns/", FleetUID, ".xml"));
            }
            else if (File.Exists(string.Concat("Content/FleetDesigns/", FleetUID, ".xml")))
            {
                theFleetFI = new FileInfo(string.Concat("Content/FleetDesigns/", FleetUID, ".xml"));
            }
            else
            {
                string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                theFleetFI = new FileInfo(string.Concat(path, "/StarDrive/Fleet Designs/", FleetUID, ".xml"));
            }
            XmlSerializer serializer1 = new XmlSerializer(typeof(FleetDesign));
            FleetDesign data = (FleetDesign)serializer1.Deserialize(theFleetFI.OpenRead());
            Fleet fleet = new Fleet()
            {
                Position = Position,
                Owner = Owner,
                DataNodes = new BatchRemovalCollection<FleetDataNode>()
            };
            foreach (FleetDataNode node in data.Data)
            {
                fleet.DataNodes.Add(node);
            }
            fleet.Name = data.Name;
            fleet.FleetIconIndex = data.FleetIconIndex;
            fleet.DataNodes.thisLock.EnterWriteLock();
            foreach (FleetDataNode node in fleet.DataNodes)
            {
                Ship s = ResourceManager.CreateShipAtPoint(node.ShipName, Owner, Position + node.FleetOffset);
                s.RelativeFleetOffset = node.FleetOffset;
                node.SetShip(s);
                fleet.AddShip(s);
            }
            fleet.DataNodes.thisLock.ExitWriteLock();
            foreach (Ship s in Owner.GetFleetsDict()[1].Ships)
            {
                s.fleet = null;
            }
            Owner.GetFleetsDict()[1] = fleet;
        }
 public static void CreateFleetFromDataAt(FleetDesign data, Empire Owner, Vector2 Position, float facing)
 {
     Fleet fleet = new Fleet()
     {
         Position = Position,
         facing = facing,
         Owner = Owner,
         DataNodes = new BatchRemovalCollection<FleetDataNode>()
     };
     foreach (FleetDataNode node in data.Data)
     {
         fleet.DataNodes.Add(node);
     }
     fleet.AssignDataPositions(facing);
     fleet.Name = data.Name;
     fleet.FleetIconIndex = data.FleetIconIndex;
     fleet.DataNodes.thisLock.EnterWriteLock();
     foreach (FleetDataNode node in fleet.DataNodes)
     {
         Ship s = ResourceManager.CreateShipAtPoint(node.ShipName, Owner, Position + node.OrdersOffset, facing);
         s.RelativeFleetOffset = node.FleetOffset;
         node.SetShip(s);
         fleet.AddShip(s);
     }
     fleet.DataNodes.thisLock.ExitWriteLock();
     foreach (Ship s in Owner.GetFleetsDict()[1].Ships)
     {
         s.fleet = null;
     }
     Owner.GetFleetsDict()[1] = fleet;
 }
        private void LoadEverything(object sender, RunWorkerCompletedEventArgs ev)
        {
            bool stop;
            List<SolarSystem>.Enumerator enumerator;
            base.ScreenManager.inter.ObjectManager.Clear();
            this.data = new UniverseData();
            RandomEventManager.ActiveEvent = this.savedData.RandomEvent;
            UniverseScreen.DeepSpaceManager = new SpatialManager();
            this.ThrusterEffect = base.ScreenManager.Content.Load<Effect>("Effects/Thrust");
            int count = this.data.SolarSystemsList.Count;
            this.data.loadFogPath = this.savedData.FogMapName;
            this.data.difficulty = UniverseData.GameDifficulty.Normal;
            this.data.difficulty = this.savedData.gameDifficulty;
            this.data.Size = this.savedData.Size;
            this.data.FTLSpeedModifier = this.savedData.FTLModifier;
            this.data.EnemyFTLSpeedModifier = this.savedData.EnemyFTLModifier;
            this.data.GravityWells = this.savedData.GravityWells;
            //added by gremlin: adjuse projector radius to map size. but only normal or higher.
            //this is pretty bad as its not connected to the creating game screen code that sets the map sizes. If someone changes the map size they wont know to change this as well.
            if (this.data.Size.X > 7300000f)
            Empire.ProjectorRadius = this.data.Size.X / 70f;
            EmpireManager.EmpireList.Clear();
            if (Empire.universeScreen!=null && Empire.universeScreen.MasterShipList != null)
                Empire.universeScreen.MasterShipList.Clear();

            foreach (SavedGame.EmpireSaveData d in this.savedData.EmpireDataList)
            {
                Empire e =new Empire();
                e.data = new EmpireData();
                    e= this.CreateEmpireFromEmpireSaveData(d);
                this.data.EmpireList.Add(e);
                if (e.data.Traits.Name == this.PlayerLoyalty)
                {
                    e.AutoColonize = this.savedData.AutoColonize;
                    e.AutoExplore = this.savedData.AutoExplore;
                    e.AutoFreighters = this.savedData.AutoFreighters;
                    e.AutoBuild = this.savedData.AutoProjectors;
                }
                EmpireManager.EmpireList.Add(e);
            }
            foreach (Empire e in this.data.EmpireList)
            {
                if (e.data.AbsorbedBy == null)
                {
                    continue;
                }
                foreach (KeyValuePair<string, TechEntry> tech in EmpireManager.GetEmpireByName(e.data.AbsorbedBy).GetTDict())
                {
                    if (!tech.Value.Unlocked)
                    {
                        continue;
                    }
                    EmpireManager.GetEmpireByName(e.data.AbsorbedBy).UnlockHullsSave(tech.Key, e.data.Traits.ShipType);
                }
            }
            foreach (SavedGame.EmpireSaveData d in this.savedData.EmpireDataList)
            {
                Empire e = EmpireManager.GetEmpireByName(d.Name);
                foreach (Relationship r in d.Relations)
                {
                    e.GetRelations().Add(EmpireManager.GetEmpireByName(r.Name), r);
                    if (r.ActiveWar == null)
                    {
                        continue;
                    }
                    r.ActiveWar.SetCombatants(e, EmpireManager.GetEmpireByName(r.Name));
                }
            }
            this.data.SolarSystemsList = new List<SolarSystem>();
            foreach (SavedGame.SolarSystemSaveData sdata in this.savedData.SolarSystemDataList)
            {
                SolarSystem system = this.CreateSystemFromData(sdata);
                system.guid = sdata.guid;
                this.data.SolarSystemsList.Add(system);
            }
            foreach (SavedGame.EmpireSaveData d in this.savedData.EmpireDataList)
            {
                Empire e = EmpireManager.GetEmpireByName(d.empireData.Traits.Name);
                foreach (SavedGame.ShipSaveData shipData in d.OwnedShips)
                {
                    Ship ship = Ship.LoadSavedShip(shipData.data);
                    ship.guid = shipData.guid;
                    ship.Name = shipData.Name;
                    if (!string.IsNullOrEmpty(shipData.VanityName))
                        ship.VanityName = shipData.VanityName;
                    else
                    {
                        if (ship.Role == "troop")
                        {
                            if (shipData.TroopList.Count > 0)
                            {
                                ship.VanityName = shipData.TroopList[0].Name;
                            }
                            else
                                ship.VanityName = shipData.Name;
                        }
                        else
                            ship.VanityName = shipData.Name;
                    }
                    ship.Position = shipData.Position;
                    if (shipData.IsPlayerShip)
                    {
                        this.playerShip = ship;
                        this.playerShip.PlayerShip = true;
                        this.data.playerShip = this.playerShip;
                    }
                    ship.experience = shipData.experience;
                    ship.kills = shipData.kills;
                    if (!Ship_Game.ResourceManager.ShipsDict.ContainsKey(shipData.Name))
                    {
                        shipData.data.Hull = shipData.Hull;
                        Ship newShip = Ship.CreateShipFromShipData(shipData.data);
                        newShip.SetShipData(shipData.data);
                        if (!newShip.InitForLoad())
                        {
                            continue;
                        }
                        newShip.InitializeStatus();
                        newShip.IsPlayerDesign = false;
                        newShip.FromSave = true;
                        Ship_Game.ResourceManager.ShipsDict.Add(shipData.Name, newShip);
                    }
                    else if (Ship_Game.ResourceManager.ShipsDict[shipData.Name].FromSave)
                    {
                        ship.IsPlayerDesign = false;
                        ship.FromSave = true;
                    }
                    float oldbasestr = ship.BaseStrength;
                    float newbasestr = ResourceManager.CalculateBaseStrength(ship);
                    ship.BaseStrength = newbasestr;

                    foreach(ModuleSlotData moduleSD in shipData.data.ModuleSlotList)
                    {
                        ShipModule mismatch =null;
                        bool exists =ResourceManager.ShipModulesDict.TryGetValue(moduleSD.InstalledModuleUID,out mismatch);
                        if (exists)
                            continue;
                        System.Diagnostics.Debug.WriteLine(string.Concat("mismatch =", moduleSD.InstalledModuleUID));
                    }

                    ship.PowerCurrent = shipData.Power;
                    ship.yRotation = shipData.yRotation;
                    ship.Ordinance = shipData.Ordnance;
                    ship.Rotation = shipData.Rotation;
                    ship.Velocity = shipData.Velocity;
                    ship.isSpooling = shipData.AfterBurnerOn;
                    ship.InCombatTimer = shipData.InCombatTimer;
                    foreach (Troop t in shipData.TroopList)
                    {
                        t.SetOwner(EmpireManager.GetEmpireByName(t.OwnerString));
                        ship.TroopList.Add(t);
                    }

                    foreach (Rectangle AOO in shipData.AreaOfOperation)
                    {
                        ship.AreaOfOperation.Add(AOO);
                    }
                    ship.TetherGuid = shipData.TetheredTo;
                    ship.TetherOffset = shipData.TetherOffset;
                    if (ship.InCombatTimer > 0f)
                    {
                        ship.InCombat = true;
                    }
                    ship.loyalty = e;
                    ship.InitializeAI();
                    ship.GetAI().CombatState = shipData.data.CombatState;
                    ship.GetAI().FoodOrProd = shipData.AISave.FoodOrProd;
                    ship.GetAI().State = shipData.AISave.state;
                    ship.GetAI().DefaultAIState = shipData.AISave.defaultstate;
                    ship.GetAI().GotoStep = shipData.AISave.GoToStep;
                    ship.GetAI().MovePosition = shipData.AISave.MovePosition;
                    ship.GetAI().OrbitTargetGuid = shipData.AISave.OrbitTarget;
                    ship.GetAI().ColonizeTargetGuid = shipData.AISave.ColonizeTarget;
                    ship.GetAI().TargetGuid = shipData.AISave.AttackTarget;
                    ship.GetAI().SystemToDefendGuid = shipData.AISave.SystemToDefend;
                    ship.GetAI().EscortTargetGuid = shipData.AISave.EscortTarget;
                    bool hasCargo = false;
                    if (shipData.FoodCount > 0f)
                    {
                        ship.AddGood("Food", (int)shipData.FoodCount);
                        ship.GetAI().FoodOrProd = "Food";
                        hasCargo = true;
                    }
                    if (shipData.ProdCount > 0f)
                    {
                        ship.AddGood("Production", (int)shipData.ProdCount);
                        ship.GetAI().FoodOrProd = "Prod";
                        hasCargo = true;
                    }
                    if (shipData.PopCount > 0f)
                    {
                        ship.AddGood("Colonists_1000", (int)shipData.PopCount);
                    }
                    AIState state = ship.GetAI().State;
                    if (state == AIState.SystemTrader)
                    {
                        ship.GetAI().OrderTradeFromSave(hasCargo, shipData.AISave.startGuid, shipData.AISave.endGuid);
                    }
                    else if (state == AIState.PassengerTransport)
                    {
                        ship.GetAI().OrderTransportPassengersFromSave();
                    }
                    e.AddShip(ship);
                    foreach (SavedGame.ProjectileSaveData pdata in shipData.Projectiles)
                    {
                        Weapon w = Ship_Game.ResourceManager.GetWeapon(pdata.Weapon);
                        Projectile p = w.LoadProjectiles(pdata.Velocity, ship);
                        p.Velocity = pdata.Velocity;
                        p.Position = pdata.Position;
                        p.Center = pdata.Position;
                        p.duration = pdata.Duration;
                        ship.Projectiles.Add(p);
                    }
                    this.data.MasterShipList.Add(ship);
                }
            }
            foreach (SavedGame.EmpireSaveData d in this.savedData.EmpireDataList)
            {
                Empire e = EmpireManager.GetEmpireByName(d.Name);
                foreach (SavedGame.FleetSave fleetsave in d.FleetsList)
                {
                    Ship_Game.Gameplay.Fleet fleet = new Ship_Game.Gameplay.Fleet()
                    {
                        guid = fleetsave.FleetGuid,
                        IsCoreFleet = fleetsave.IsCoreFleet,
                        facing = fleetsave.facing
                    };
                    foreach (SavedGame.FleetShipSave ssave in fleetsave.ShipsInFleet)
                    {
                        foreach (Ship ship in this.data.MasterShipList)
                        {
                            if (ship.guid != ssave.shipGuid)
                            {
                                continue;
                            }
                            ship.RelativeFleetOffset = ssave.fleetOffset;
                            fleet.AddShip(ship);
                        }
                    }
                    foreach (FleetDataNode node in fleetsave.DataNodes)
                    {
                        fleet.DataNodes.Add(node);
                    }
                    foreach (FleetDataNode node in fleet.DataNodes)
                    {
                        foreach (Ship ship in fleet.Ships)
                        {
                            if (!(node.ShipGuid != Guid.Empty) || !(ship.guid == node.ShipGuid))
                            {
                                continue;
                            }
                            node.SetShip(ship);
                            node.ShipName = ship.Name;
                            break;
                        }
                    }
                    fleet.AssignPositions(fleet.facing);
                    fleet.Name = fleetsave.Name;
                    fleet.TaskStep = fleetsave.TaskStep;
                    fleet.Owner = e;
                    fleet.Position = fleetsave.Position;

                    if (e.GetFleetsDict().ContainsKey(fleetsave.Key))
                    {
                        e.GetFleetsDict()[fleetsave.Key] = fleet;
                    }
                    else
                    {
                        e.GetFleetsDict().TryAdd(fleetsave.Key, fleet);
                    }
                    e.GetFleetsDict()[fleetsave.Key].SetSpeed();
                    fleet.findAveragePositionset();
                    fleet.Setavgtodestination();

                }
                foreach (SavedGame.ShipSaveData shipData in d.OwnedShips)
                {
                    foreach (Ship ship in e.GetShips())
                    {
                        if (ship.Position != shipData.Position)
                        {
                            continue;
                        }
                    }
                }
            }
            foreach (SavedGame.EmpireSaveData d in this.savedData.EmpireDataList)
            {
                Empire e = EmpireManager.GetEmpireByName(d.Name);
                e.SpaceRoadsList = new List<SpaceRoad>();
                foreach (SavedGame.SpaceRoadSave roadsave in d.SpaceRoadData)
                {
                    SpaceRoad road = new SpaceRoad();
                    foreach (SolarSystem s in this.data.SolarSystemsList)
                    {
                        if (roadsave.OriginGUID == s.guid)
                        {
                            road.SetOrigin(s);
                        }
                        if (roadsave.DestGUID != s.guid)
                        {
                            continue;
                        }
                        road.SetDestination(s);
                    }
                    foreach (SavedGame.RoadNodeSave nodesave in roadsave.RoadNodes)
                    {
                        RoadNode node = new RoadNode();
                        foreach (Ship s in this.data.MasterShipList)
                        {
                            if (nodesave.Guid_Platform != s.guid)
                            {
                                continue;
                            }
                            node.Platform = s;
                        }
                        node.Position = nodesave.Position;
                        road.RoadNodesList.Add(node);
                    }
                    e.SpaceRoadsList.Add(road);
                }
                foreach (SavedGame.GoalSave gsave in d.GSAIData.Goals)
                {
                    Goal g = new Goal()
                    {
                        empire = e,
                        type = gsave.type
                    };
                    if (g.type == GoalType.BuildShips && gsave.ToBuildUID != null && !Ship_Game.ResourceManager.ShipsDict.ContainsKey(gsave.ToBuildUID))
                    {
                        continue;
                    }
                    g.ToBuildUID = gsave.ToBuildUID;
                    g.Step = gsave.GoalStep;
                    g.guid = gsave.GoalGuid;
                    g.GoalName = gsave.GoalName;
                    g.BuildPosition = gsave.BuildPosition;
                    if (gsave.fleetGuid != Guid.Empty)
                    {
                        foreach (KeyValuePair<int, Ship_Game.Gameplay.Fleet> Fleet in e.GetFleetsDict())
                        {
                            if (Fleet.Value.guid != gsave.fleetGuid)
                            {
                                continue;
                            }
                            g.SetFleet(Fleet.Value);
                        }
                    }
                    foreach (SolarSystem s in this.data.SolarSystemsList)
                    {
                        foreach (Planet p in s.PlanetList)
                        {
                            if (p.guid == gsave.planetWhereBuildingAtGuid)
                            {
                                g.SetPlanetWhereBuilding(p);
                            }
                            if (p.guid != gsave.markedPlanetGuid)
                            {
                                continue;
                            }
                            g.SetMarkedPlanet(p);
                        }
                    }
                    foreach (Ship s in this.data.MasterShipList)
                    {
                        if (gsave.colonyShipGuid == s.guid)
                        {
                            g.SetColonyShip(s);
                        }
                        if (gsave.beingBuiltGUID != s.guid)
                        {
                            continue;
                        }
                        g.SetBeingBuilt(s);
                    }
                    e.GetGSAI().Goals.Add(g);
                }
                for (int i = 0; i < d.GSAIData.PinGuids.Count; i++)
                {
                    e.GetGSAI().ThreatMatrix.Pins.TryAdd(d.GSAIData.PinGuids[i], d.GSAIData.PinList[i]);
                }
                e.GetGSAI().UsedFleets = d.GSAIData.UsedFleets;
                lock (GlobalStats.TaskLocker)
                {
                    foreach (MilitaryTask task in d.GSAIData.MilitaryTaskList)
                    {
                        task.SetEmpire(e);
                        e.GetGSAI().TaskList.Add(task);
                        if (task.TargetPlanetGuid != Guid.Empty)
                        {
                            enumerator = this.data.SolarSystemsList.GetEnumerator();
                            try
                            {
                                do
                                {
                                    if (!enumerator.MoveNext())
                                    {
                                        break;
                                    }
                                    SolarSystem s = enumerator.Current;
                                    stop = false;
                                    foreach (Planet p in s.PlanetList)
                                    {
                                        if (p.guid != task.TargetPlanetGuid)
                                        {
                                            continue;
                                        }
                                        task.SetTargetPlanet(p);
                                        stop = true;
                                        break;
                                    }
                                }
                                while (!stop);
                            }
                            finally
                            {
                                ((IDisposable)enumerator).Dispose();
                            }
                        }
                        foreach (Guid guid in task.HeldGoals)
                        {
                            foreach (Goal g in e.GetGSAI().Goals)
                            {
                                if (g.guid != guid)
                                {
                                    continue;
                                }
                                g.Held = true;
                            }
                        }
                        try
                        {
                            if (task.WhichFleet != -1)
                            {
                                e.GetFleetsDict()[task.WhichFleet].Task = task;
                            }
                        }
                        catch
                        {
                            task.WhichFleet = 0;
                        }
                    }
                }
                foreach (SavedGame.ShipSaveData shipData in d.OwnedShips)
                {
                    foreach (Ship ship in this.data.MasterShipList)
                    {
                        if (ship.guid != shipData.guid)
                        {
                            continue;
                        }
                        foreach (Vector2 waypoint in shipData.AISave.ActiveWayPoints)
                        {
                            ship.GetAI().ActiveWayPoints.Enqueue(waypoint);
                        }
                        foreach (SavedGame.ShipGoalSave sg in shipData.AISave.ShipGoalsList)
                        {
                            ArtificialIntelligence.ShipGoal g = new ArtificialIntelligence.ShipGoal(sg.Plan, sg.MovePosition, sg.FacingVector);
                            foreach (SolarSystem s in this.data.SolarSystemsList)
                            {
                                foreach (Planet p in s.PlanetList)
                                {
                                    if (sg.TargetPlanetGuid == p.guid)
                                    {
                                        g.TargetPlanet = p;
                                        ship.GetAI().ColonizeTarget = p;
                                    }
                                    if (p.guid == shipData.AISave.startGuid)
                                    {
                                        ship.GetAI().start = p;
                                    }
                                    if (p.guid != shipData.AISave.endGuid)
                                    {
                                        continue;
                                    }
                                    ship.GetAI().end = p;
                                }
                            }
                            if (sg.fleetGuid != Guid.Empty)
                            {
                                foreach (KeyValuePair<int, Ship_Game.Gameplay.Fleet> fleet in e.GetFleetsDict())
                                {
                                    if (fleet.Value.guid != sg.fleetGuid)
                                    {
                                        continue;
                                    }
                                    g.fleet = fleet.Value;
                                }
                            }
                            g.VariableString = sg.VariableString;
                            g.DesiredFacing = sg.DesiredFacing;
                            g.SpeedLimit = sg.SpeedLimit;
                            foreach (Goal goal in ship.loyalty.GetGSAI().Goals)
                            {
                                if (sg.goalGuid != goal.guid)
                                {
                                    continue;
                                }
                                g.goal = goal;
                            }
                            ship.GetAI().OrderQueue.AddLast(g);
                        }
                    }
                }
            }
            foreach (SavedGame.SolarSystemSaveData sdata in this.savedData.SolarSystemDataList)
            {
                foreach (SavedGame.RingSave rsave in sdata.RingList)
                {
                    Planet p = new Planet();
                    foreach (SolarSystem s in this.data.SolarSystemsList)
                    {
                        foreach (Planet p1 in s.PlanetList)
                        {
                            if (p1.guid != rsave.Planet.guid)
                            {
                                continue;
                            }
                            p = p1;
                            break;
                        }
                    }
                    if (p.Owner == null)
                    {
                        continue;
                    }
                    foreach (SavedGame.QueueItemSave qisave in rsave.Planet.QISaveList)
                    {
                        QueueItem qi = new QueueItem();
                        if (qisave.isBuilding)
                        {
                            qi.isBuilding = true;
                            qi.Building = Ship_Game.ResourceManager.BuildingsDict[qisave.UID];
                            qi.Cost = qi.Building.Cost * this.savedData.GamePacing;
                            qi.NotifyOnEmpty = false;
                            foreach (PlanetGridSquare pgs in p.TilesList)
                            {
                                if ((float)pgs.x != qisave.pgsVector.X || (float)pgs.y != qisave.pgsVector.Y)
                                {
                                    continue;
                                }
                                pgs.QItem = qi;
                                qi.pgs = pgs;
                                break;
                            }
                        }
                        if (qisave.isTroop)
                        {
                            qi.isTroop = true;
                            qi.troop = Ship_Game.ResourceManager.TroopsDict[qisave.UID];
                            qi.Cost = qi.troop.GetCost();
                            qi.NotifyOnEmpty = false;
                        }
                        if (qisave.isShip)
                        {
                            qi.isShip = true;
                            if (!Ship_Game.ResourceManager.ShipsDict.ContainsKey(qisave.UID))
                            {
                                continue;
                            }
                            qi.sData = Ship_Game.ResourceManager.GetShip(qisave.UID).GetShipData();
                            qi.DisplayName = qisave.DisplayName;
                            qi.Cost = 0f;
                            foreach (ModuleSlot slot in Ship_Game.ResourceManager.GetShip(qisave.UID).ModuleSlotList)
                            {
                                if (slot.InstalledModuleUID == null)
                                {
                                    continue;
                                }
                                QueueItem cost = qi;
                                cost.Cost = cost.Cost + Ship_Game.ResourceManager.GetModule(slot.InstalledModuleUID).Cost * this.savedData.GamePacing;
                            }
                            QueueItem queueItem = qi;
                            queueItem.Cost += qi.Cost * p.Owner.data.Traits.ShipCostMod;
                            queueItem.Cost *= (GlobalStats.ActiveModInfo != null && GlobalStats.ActiveModInfo.useHullBonuses && ResourceManager.HullBonuses.ContainsKey(Ship_Game.ResourceManager.GetShip(qisave.UID).GetShipData().Hull) ? 1f - ResourceManager.HullBonuses[Ship_Game.ResourceManager.GetShip(qisave.UID).GetShipData().Hull].CostBonus : 1);
                            if (qi.sData.HasFixedCost)
                            {
                                qi.Cost = (float)qi.sData.FixedCost;
                            }
                            if (qisave.IsRefit)
                            {
                                qi.isRefit = true;
                                qi.Cost = qisave.RefitCost;
                            }
                        }
                        foreach (Goal g in p.Owner.GetGSAI().Goals)
                        {
                            if (g.guid != qisave.GoalGUID)
                            {
                                continue;
                            }
                            qi.Goal = g;
                            qi.NotifyOnEmpty = false;
                        }
                        if (qisave.isShip && qi.Goal != null)
                        {
                            qi.Goal.beingBuilt = Ship_Game.ResourceManager.GetShip(qisave.UID);
                        }
                        qi.productionTowards = qisave.ProgressTowards;
                        p.ConstructionQueue.Add(qi);
                    }
                }
            }
            this.Loaded = true;
        }
        protected void HandleRightMouseNew(InputState input)
        {
            if (this.SkipRightOnce)
            {
                if (input.CurrentMouseState.RightButton != ButtonState.Released || input.LastMouseState.RightButton != ButtonState.Released)
                    return;
                this.SkipRightOnce = false;
            }
            else
            {
                Viewport viewport;
                if (input.CurrentMouseState.RightButton == ButtonState.Pressed && input.LastMouseState.RightButton == ButtonState.Released)
                {
                    this.SelectedSomethingTimer = 3f;
                    this.startDrag = new Vector2((float)input.CurrentMouseState.X, (float)input.CurrentMouseState.Y);
                    this.startDragWorld = this.GetWorldSpaceFromScreenSpace(this.startDrag);
                    this.ProjectedPosition = this.GetWorldSpaceFromScreenSpace(this.startDrag);
                    Vector3 position = this.ScreenManager.GraphicsDevice.Viewport.Unproject(new Vector3((float)input.CurrentMouseState.X, (float)input.CurrentMouseState.Y, 0.0f), this.projection, this.view, Matrix.Identity);
                    viewport = this.ScreenManager.GraphicsDevice.Viewport;
                    Vector3 direction = viewport.Unproject(new Vector3((float)input.CurrentMouseState.X, (float)input.CurrentMouseState.Y, 1f), this.projection, this.view, Matrix.Identity) - position;
                    direction.Normalize();
                    Ray ray = new Ray(position, direction);
                    float num = -ray.Position.Z / ray.Direction.Z;
                    Vector3 vector3 = new Vector3(ray.Position.X + num * ray.Direction.X, ray.Position.Y + num * ray.Direction.Y, 0.0f);
                }
                if (this.SelectedShip != null && this.SelectedShip.GetAI().State == AIState.ManualControl && (double)Vector2.Distance(this.startDragWorld, this.SelectedShip.Center) < 5000.0)
                    return;
                if (input.CurrentMouseState.RightButton == ButtonState.Released && input.LastMouseState.RightButton == ButtonState.Pressed)
                {
                    viewport = this.ScreenManager.GraphicsDevice.Viewport;
                    Vector3 position = viewport.Unproject(new Vector3((float)input.CurrentMouseState.X, (float)input.CurrentMouseState.Y, 0.0f), this.projection, this.view, Matrix.Identity);
                    viewport = this.ScreenManager.GraphicsDevice.Viewport;
                    Vector3 direction = viewport.Unproject(new Vector3((float)input.CurrentMouseState.X, (float)input.CurrentMouseState.Y, 1f), this.projection, this.view, Matrix.Identity) - position;
                    direction.Normalize();
                    Ray ray = new Ray(position, direction);
                    float num1 = -ray.Position.Z / ray.Direction.Z;
                    Vector3 vector3 = new Vector3(ray.Position.X + num1 * ray.Direction.X, ray.Position.Y + num1 * ray.Direction.Y, 0.0f);
                    Vector2 vector2_1 = new Vector2(vector3.X, vector3.Y);
                    Vector2 target = new Vector2((float)input.CurrentMouseState.X, (float)input.CurrentMouseState.Y);
                    float num2 = Math.Abs(MathHelper.ToRadians(this.findAngleToTarget(this.startDrag, target)));
                    Vector2 vector2_2 = Vector2.Normalize(target - this.startDrag);
                    if ((double)input.RightMouseTimer > 0.0)
                    {
                        if (this.SelectedFleet != null && this.SelectedFleet.Owner == this.player)
                        {
                            AudioManager.PlayCue("echo_affirm1");
                            this.SelectedSomethingTimer = 3f;
                            float num3 = Math.Abs(MathHelper.ToRadians(this.findAngleToTarget(this.SelectedFleet.Position, vector2_1)));
                            Vector2 vectorToTarget = HelperFunctions.FindVectorToTarget(Vector2.Zero, HelperFunctions.findPointFromAngleAndDistanceUsingRadians(this.SelectedFleet.Position, num3, 1f));
                            foreach (Ship ship in (List<Ship>)this.SelectedFleet.Ships)
                                this.player.GetGSAI().DefensiveCoordinator.remove(ship);
                            Ship ship1 = this.CheckShipClick(this.startDrag);
                            Planet planet;
                            lock (GlobalStats.ClickableSystemsLock)
                                planet = this.CheckPlanetClick(this.startDrag);
                            if (ship1 != null && ship1.loyalty != this.player)
                            {
                                this.SelectedFleet.Position = ship1.Center;
                                this.SelectedFleet.AssignPositions(0.0f);
                                foreach (Ship ship2 in (List<Ship>)this.SelectedFleet.Ships)
                                {
                                    if (ship2.Role == "troop")
                                        ship2.GetAI().OrderTroopToBoardShip(ship1);
                                    else if (input.CurrentKeyboardState.IsKeyDown(Keys.LeftShift))
                                        ship2.GetAI().OrderQueueSpecificTarget(ship1);
                                    else
                                        ship2.GetAI().OrderAttackSpecificTarget(ship1);
                                }
                            }
                            else if (planet != null)
                            {
                                foreach (Ship ship2 in (List<Ship>)this.SelectedFleet.Ships)
                                {
                                    RightClickship(ship2, planet,false);
                                }
                            }
                            else if (input.CurrentKeyboardState.IsKeyDown(Keys.LeftShift))
                                this.SelectedFleet.FormationWarpToQ(vector2_1, num3, vectorToTarget);
                            else if (input.CurrentKeyboardState.IsKeyDown(Keys.LeftAlt))
                                this.SelectedFleet.MoveToDirectly(vector2_1, num3, vectorToTarget);
                            else
                                this.SelectedFleet.FormationWarpTo(vector2_1, num3, vectorToTarget);
                        }
                        else if (this.SelectedShip != null && this.SelectedShip.loyalty == this.player)
                        {
                            this.player.GetGSAI().DefensiveCoordinator.DefensiveForcePool.Remove(this.SelectedShip);
                            this.SelectedSomethingTimer = 3f;
                            Ship ship = this.CheckShipClick(this.startDrag);
                            Planet planet;
                            lock (GlobalStats.ClickableSystemsLock)
                                planet = this.CheckPlanetClick(this.startDrag);
                            if (ship != null && ship != this.SelectedShip)
                            #region Target Ship
                            {
                                if (this.SelectedShip.Role == "construction")
                                {
                                    AudioManager.PlayCue("UI_Misc20");
                                    return;
                                }
                                else
                                {
                                    AudioManager.PlayCue("echo_affirm1");
                                    if (ship.loyalty == this.player)
                                    {
                                        if (this.SelectedShip.Role == "troop")
                                        {
                                            if (ship.TroopList.Count < ship.TroopCapacity)
                                                this.SelectedShip.GetAI().OrderTroopToShip(ship);
                                            else
                                                this.SelectedShip.DoEscort(ship);
                                        }
                                        else
                                            this.SelectedShip.DoEscort(ship);
                                    }
                                    else if (this.SelectedShip.Role == "troop")
                                        this.SelectedShip.GetAI().OrderTroopToBoardShip(ship);
                                    else if (input.CurrentKeyboardState.IsKeyDown(Keys.LeftShift))
                                        this.SelectedShip.GetAI().OrderQueueSpecificTarget(ship);
                                    else
                                        this.SelectedShip.GetAI().OrderAttackSpecificTarget(ship);
                                }
                            }
                            #endregion
                            else if (ship != null && ship == this.SelectedShip)
                            {
                                if (ship.loyalty == this.player)
                                    this.LoadShipMenuNodes(1);
                                else
                                    this.LoadShipMenuNodes(0);
                                if (!this.pieMenu.Visible)
                                {
                                    this.pieMenu.RootNode = this.shipMenu;
                                    this.pieMenu.Show(this.pieMenu.Position);
                                }
                                else
                                    this.pieMenu.ChangeTo((PieMenuNode)null);
                            }
                            else if (planet != null)
                            {

                                RightClickship(this.SelectedShip, planet,true);

                            }
                            else if (this.SelectedShip.Role == "construction")
                            {
                                AudioManager.PlayCue("UI_Misc20");
                                return;
                            }
                            else
                            {
                                AudioManager.PlayCue("echo_affirm1");
                                if (input.CurrentKeyboardState.IsKeyDown(Keys.LeftShift))
                                {
                                    if (input.CurrentKeyboardState.IsKeyDown(Keys.LeftAlt))
                                        this.SelectedShip.GetAI().OrderMoveDirectlyTowardsPosition(vector2_1, num2, vector2_2, false);
                                    else
                                        this.SelectedShip.GetAI().OrderMoveTowardsPosition(vector2_1, num2, vector2_2, false,null);
                                }
                                else if (input.CurrentKeyboardState.IsKeyDown(Keys.LeftAlt))
                                    this.SelectedShip.GetAI().OrderMoveDirectlyTowardsPosition(vector2_1, num2, vector2_2, true);
                                else if (input.CurrentKeyboardState.IsKeyDown(Keys.LeftControl))
                                {
                                    this.SelectedShip.GetAI().OrderMoveTowardsPosition(vector2_1, num2, vector2_2, true,null);
                                    this.SelectedShip.GetAI().OrderQueue.AddLast(new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.HoldPosition, vector2_1, num2));
                                    this.SelectedShip.GetAI().HasPriorityOrder = true;
                                    this.SelectedShip.GetAI().IgnoreCombat = true;
                                }
                                else
                                    this.SelectedShip.GetAI().OrderMoveTowardsPosition(vector2_1, num2, vector2_2, true,null);
                            }
                        }
                        else if (this.SelectedShipList.Count > 0)
                        {
                            this.SelectedSomethingTimer = 3f;
                            foreach (Ship ship in (List<Ship>)this.SelectedShipList)
                            {
                                if (ship.loyalty != this.player || ship.Role == "construction")
                                {
                                    AudioManager.PlayCue("UI_Misc20");
                                    return;
                                }
                            }
                            AudioManager.PlayCue("echo_affirm1");
                            Ship ship1 = this.CheckShipClick(this.startDrag);
                            Planet planet;
                            lock (GlobalStats.ClickableSystemsLock)
                                planet = this.CheckPlanetClick(this.startDrag);
                            if (ship1 != null || planet != null)
                            #region Target Planet
                            {
                                foreach (Ship ship2 in (List<Ship>)this.SelectedShipList)
                                {
                                    this.player.GetGSAI().DefensiveCoordinator.remove(ship2);
                                    if (ship1 != null && ship1 != ship2)
                                    {
                                        if (ship1.loyalty == this.player)
                                        {
                                            if (ship2.Role == "troop")
                                            {
                                                if (ship1.TroopList.Count < ship1.TroopCapacity)
                                                    ship2.GetAI().OrderTroopToShip(ship1);
                                                else
                                                    ship2.DoEscort(ship1);
                                            }
                                            else
                                                ship2.DoEscort(ship1);
                                        }
                                        else if (ship2.Role == "troop")
                                            ship2.GetAI().OrderTroopToBoardShip(ship1);
                                        else if (input.CurrentKeyboardState.IsKeyDown(Keys.LeftShift))
                                            ship2.GetAI().OrderQueueSpecificTarget(ship1);
                                        else
                                            ship2.GetAI().OrderAttackSpecificTarget(ship1);
                                    }
                                    else if (planet != null)
                                    {
                                        RightClickship(ship2, planet, false);

                                    }
                                }
                            }
                            #endregion
                            else
                            {
                                this.SelectedSomethingTimer = 3f;
                                foreach (Ship ship2 in (List<Ship>)this.SelectedShipList)
                                {
                                    if (ship2.Role == "construction")
                                    {
                                        this.SelectedShipList.Clear();
                                        AudioManager.PlayCue("UI_Misc20");
                                        return;
                                    }
                                }
                                AudioManager.PlayCue("echo_affirm1");
                                this.endDragWorld = this.GetWorldSpaceFromScreenSpace(input.CursorPosition);
                                Enumerable.OrderBy<Ship, float>((IEnumerable<Ship>)this.SelectedShipList, (Func<Ship, float>)(ship => ship.Center.X));
                                Vector2 fVec = new Vector2(-vector2_2.Y, vector2_2.X);
                                float num3 = Vector2.Distance(this.endDragWorld, this.startDragWorld);
                                int num4 = 0;
                                int num5 = 0;
                                float num6 = 0.0f;
                                for (int index = 0; index < this.SelectedShipList.Count; ++index)
                                {
                                    this.player.GetGSAI().DefensiveCoordinator.remove(this.SelectedShipList[index]);
                                    if ((double)this.SelectedShipList[index].GetSO().WorldBoundingSphere.Radius > (double)num6)
                                        num6 = this.SelectedShipList[index].GetSO().WorldBoundingSphere.Radius;
                                }
                                Fleet fleet = new Fleet();
                                if ((double)this.SelectedShipList.Count * (double)num6 > (double)num3)
                                {
                                    for (int index = 0; index < this.SelectedShipList.Count; ++index)
                                    {
                                        fleet.AddShip(this.SelectedShipList[index].SoftCopy());
                                        fleet.Ships[index].RelativeFleetOffset = new Vector2((num6 + 200f) * (float)num5, (float)num4 * (num6 + 200f));
                                        ++num5;
                                        if ((double)fleet.Ships[index].RelativeFleetOffset.X + (double)num6 > (double)num3)
                                        {
                                            num5 = 0;
                                            ++num4;
                                        }
                                    }
                                }
                                else
                                {
                                    float num7 = num3 / (float)this.SelectedShipList.Count;
                                    for (int index = 0; index < this.SelectedShipList.Count; ++index)
                                    {
                                        fleet.AddShip(this.SelectedShipList[index].SoftCopy());
                                        fleet.Ships[index].RelativeFleetOffset = new Vector2(num7 * (float)index, 0.0f);
                                    }
                                }
                                fleet.ProjectPos(this.endDragWorld, num2 - 1.570796f, fVec);
                                foreach (Ship ship2 in (List<Ship>)fleet.Ships)
                                {
                                    foreach (Ship ship3 in (List<Ship>)this.SelectedShipList)
                                    {
                                        if (ship2.guid == ship3.guid)
                                        {
                                            if (input.CurrentKeyboardState.IsKeyDown(Keys.LeftShift))
                                            {
                                                if (input.CurrentKeyboardState.IsKeyDown(Keys.LeftAlt))
                                                    ship3.GetAI().OrderMoveDirectlyTowardsPosition(ship2.projectedPosition, num2 - 1.570796f, fVec, false);
                                                else
                                                    ship3.GetAI().OrderMoveTowardsPosition(ship2.projectedPosition, num2 - 1.570796f, fVec, false,null);
                                            }
                                            else if (input.CurrentKeyboardState.IsKeyDown(Keys.LeftAlt))
                                                ship3.GetAI().OrderMoveDirectlyTowardsPosition(ship2.projectedPosition, num2 - 1.570796f, fVec, true);
                                            else
                                                ship3.GetAI().OrderMoveTowardsPosition(ship2.projectedPosition, num2 - 1.570796f, fVec, true,null);
                                        }
                                    }
                                }
                                this.projectedGroup = (ShipGroup)fleet;
                                fleet.Reset();
                            }
                        }
                        if (this.SelectedFlank == null && this.SelectedFleet == null && (this.SelectedItem == null && this.SelectedShip == null) && (this.SelectedPlanet == null && this.SelectedShipList.Count == 0))
                        {
                            Ship ship = this.CheckShipClick(input.CursorPosition);
                            if (ship != null)
                            {
                                this.SelectedShip = ship;
                                if (ship.loyalty == this.player)
                                    this.LoadShipMenuNodes(1);
                                else
                                    this.LoadShipMenuNodes(0);
                                if (!this.pieMenu.Visible)
                                {
                                    this.pieMenu.RootNode = this.shipMenu;
                                    this.pieMenu.Show(this.pieMenu.Position);
                                }
                                else
                                    this.pieMenu.ChangeTo((PieMenuNode)null);
                            }
                        }
                    }
                    else
                    {
                        this.ProjectingPosition = true;
                        if (this.SelectedFleet != null && this.SelectedFleet.Owner == this.player)
                        {
                            this.SelectedSomethingTimer = 3f;
                            if (input.CurrentKeyboardState.IsKeyDown(Keys.LeftShift))
                                this.SelectedFleet.FormationWarpToQ(this.ProjectedPosition, num2, vector2_2);
                            else
                                this.SelectedFleet.FormationWarpTo(this.ProjectedPosition, num2, vector2_2);
                            AudioManager.PlayCue("echo_affirm1");
                            foreach (Ship ship in (List<Ship>)this.SelectedFleet.Ships)
                                this.player.GetGSAI().DefensiveCoordinator.remove(ship);
                        }
                        else if (this.SelectedShip != null && this.SelectedShip.loyalty == this.player)
                        {
                            this.player.GetGSAI().DefensiveCoordinator.remove(this.SelectedShip);
                            this.SelectedSomethingTimer = 3f;
                            if (this.SelectedShip.Role == "construction")
                            {
                                if (this.SelectedShip != null && this.SelectedShip != this.previousSelection)
                                    this.previousSelection = this.SelectedShip;
                                this.SelectedShip = (Ship)null;
                                AudioManager.PlayCue("UI_Misc20");
                                return;
                            }
                            else
                            {
                                AudioManager.PlayCue("echo_affirm1");
                                if (input.CurrentKeyboardState.IsKeyDown(Keys.LeftShift))
                                {
                                    if (input.CurrentKeyboardState.IsKeyDown(Keys.LeftAlt))
                                        this.SelectedShip.GetAI().OrderMoveDirectlyTowardsPosition(this.ProjectedPosition, num2, vector2_2, false);
                                    else
                                        this.SelectedShip.GetAI().OrderMoveTowardsPosition(this.ProjectedPosition, num2, vector2_2, false,null);
                                }
                                else if (input.CurrentKeyboardState.IsKeyDown(Keys.LeftAlt))
                                    this.SelectedShip.GetAI().OrderMoveDirectlyTowardsPosition(this.ProjectedPosition, num2, vector2_2, true);
                                else
                                    this.SelectedShip.GetAI().OrderMoveTowardsPosition(this.ProjectedPosition, num2, vector2_2, true,null);
                            }
                        }
                        else if (this.SelectedShipList.Count > 0)
                        {
                            this.SelectedSomethingTimer = 3f;
                            foreach (Ship ship in (List<Ship>)this.SelectedShipList)
                            {
                                if (ship.loyalty != this.player)
                                    return;
                                if (ship.Role == "construction")
                                {
                                    this.SelectedShipList.Clear();
                                    AudioManager.PlayCue("UI_Misc20");
                                    return;
                                }
                            }
                            AudioManager.PlayCue("echo_affirm1");
                            this.endDragWorld = this.GetWorldSpaceFromScreenSpace(input.CursorPosition);
                            Enumerable.OrderBy<Ship, float>((IEnumerable<Ship>)this.SelectedShipList, (Func<Ship, float>)(ship => ship.Center.X));
                            Vector2 fVec = new Vector2(-vector2_2.Y, vector2_2.X);
                            float num3 = Vector2.Distance(this.endDragWorld, this.startDragWorld);
                            int num4 = 0;
                            int num5 = 0;
                            float num6 = 0.0f;
                            for (int index = 0; index < this.SelectedShipList.Count; ++index)
                            {
                                this.player.GetGSAI().DefensiveCoordinator.remove(this.SelectedShipList[index]);
                                if ((double)this.SelectedShipList[index].GetSO().WorldBoundingSphere.Radius > (double)num6)
                                    num6 = this.SelectedShipList[index].GetSO().WorldBoundingSphere.Radius;
                            }
                            Fleet fleet = new Fleet();
                            if ((double)this.SelectedShipList.Count * (double)num6 > (double)num3)
                            {
                                for (int index = 0; index < this.SelectedShipList.Count; ++index)
                                {
                                    fleet.AddShip(this.SelectedShipList[index].SoftCopy());
                                    fleet.Ships[index].RelativeFleetOffset = new Vector2((num6 + 200f) * (float)num5, (float)num4 * (num6 + 200f));
                                    ++num5;
                                    if ((double)this.SelectedShipList[index].RelativeFleetOffset.X + (double)num6 > (double)num3)
                                    {
                                        num5 = 0;
                                        ++num4;
                                    }
                                }
                            }
                            else
                            {
                                float num7 = num3 / (float)this.SelectedShipList.Count;
                                for (int index = 0; index < this.SelectedShipList.Count; ++index)
                                {
                                    fleet.AddShip(this.SelectedShipList[index].SoftCopy());
                                    fleet.Ships[index].RelativeFleetOffset = new Vector2(num7 * (float)index, 0.0f);
                                }
                            }
                            fleet.ProjectPos(this.ProjectedPosition, num2 - 1.570796f, fVec);
                            foreach (Ship ship1 in (List<Ship>)fleet.Ships)
                            {
                                foreach (Ship ship2 in (List<Ship>)this.SelectedShipList)
                                {
                                    if (ship1.guid == ship2.guid)
                                    {
                                        if (input.CurrentKeyboardState.IsKeyDown(Keys.LeftShift))
                                        {
                                            if (input.CurrentKeyboardState.IsKeyDown(Keys.LeftAlt))
                                                ship2.GetAI().OrderMoveDirectlyTowardsPosition(ship1.projectedPosition, num2 - 1.570796f, fVec, false);
                                            else
                                                ship2.GetAI().OrderMoveTowardsPosition(ship1.projectedPosition, num2 - 1.570796f, fVec, false,null);
                                        }
                                        else if (input.CurrentKeyboardState.IsKeyDown(Keys.LeftAlt))
                                            ship2.GetAI().OrderMoveDirectlyTowardsPosition(ship1.projectedPosition, num2 - 1.570796f, fVec, true);
                                        else
                                            ship2.GetAI().OrderMoveTowardsPosition(ship1.projectedPosition, num2 - 1.570796f, fVec, true,null);
                                    }
                                }
                            }
                            this.projectedGroup = (ShipGroup)fleet;
                        }
                    }
                }
                if (input.CurrentMouseState.RightButton == ButtonState.Pressed && input.LastMouseState.RightButton == ButtonState.Pressed)
                {
                    Vector2 target = new Vector2((float)input.CurrentMouseState.X, (float)input.CurrentMouseState.Y);
                    float facing = Math.Abs(MathHelper.ToRadians(this.findAngleToTarget(this.startDrag, target)));
                    Vector2 fVec1 = Vector2.Normalize(target - this.startDrag);
                    if ((double)input.RightMouseTimer > 0.0)
                        return;
                    this.ProjectingPosition = true;
                    if (this.SelectedFlank != null)
                    {
                        this.SelectedFleet.ProjectPos(this.ProjectedPosition, facing, this.SelectedFlank);
                        ShipGroup shipGroup = new ShipGroup();
                        foreach (Fleet.Squad squad in this.SelectedFlank)
                        {
                            foreach (Ship ship in (List<Ship>)squad.Ships)
                                shipGroup.Ships.Add(ship);
                        }
                        shipGroup.ProjectedFacing = facing;
                        this.projectedGroup = shipGroup;
                    }
                    else if (this.SelectedFleet != null && this.SelectedFleet.Owner == this.player)
                    {
                        this.ProjectingPosition = true;
                        this.SelectedFleet.ProjectPos(this.ProjectedPosition, facing, fVec1);
                        this.projectedGroup = (ShipGroup)this.SelectedFleet;
                    }
                    else if (this.SelectedShip != null && this.SelectedShip.loyalty == this.player)
                    {
                        if (this.SelectedShip.Role == "construction")
                        {
                            this.SelectedShip = (Ship)null;
                            AudioManager.PlayCue("UI_Misc20");
                        }
                        else
                        {
                            ShipGroup shipGroup = new ShipGroup();
                            shipGroup.Ships.Add(this.SelectedShip);
                            shipGroup.ProjectPos(this.ProjectedPosition, facing, fVec1);
                            this.projectedGroup = shipGroup;
                        }
                    }
                    else
                    {
                        if (this.SelectedShipList.Count <= 0)
                            return;
                        foreach (Ship ship in (List<Ship>)this.SelectedShipList)
                        {
                            if (ship.loyalty != this.player)
                                return;
                        }
                        this.endDragWorld = this.GetWorldSpaceFromScreenSpace(input.CursorPosition);
                        Enumerable.OrderBy<Ship, float>((IEnumerable<Ship>)this.SelectedShipList, (Func<Ship, float>)(ship => ship.Center.X));
                        Vector2 fVec2 = new Vector2(-fVec1.Y, fVec1.X);
                        float num1 = Vector2.Distance(this.endDragWorld, this.startDragWorld);
                        int num2 = 0;
                        int num3 = 0;
                        float num4 = 0.0f;
                        for (int index = 0; index < this.SelectedShipList.Count; ++index)
                        {
                            if ((double)this.SelectedShipList[index].GetSO().WorldBoundingSphere.Radius > (double)num4)
                                num4 = this.SelectedShipList[index].GetSO().WorldBoundingSphere.Radius;
                        }
                        Fleet fleet = new Fleet();
                        if ((double)this.SelectedShipList.Count * (double)num4 > (double)num1)
                        {
                            for (int index = 0; index < this.SelectedShipList.Count; ++index)
                            {
                                fleet.AddShip(this.SelectedShipList[index].SoftCopy());
                                fleet.Ships[index].RelativeFleetOffset = new Vector2((num4 + 200f) * (float)num3, (float)num2 * (num4 + 200f));
                                ++num3;
                                if ((double)this.SelectedShipList[index].RelativeFleetOffset.X + (double)num4 > (double)num1)
                                {
                                    num3 = 0;
                                    ++num2;
                                }
                            }
                        }
                        else
                        {
                            float num5 = num1 / (float)this.SelectedShipList.Count;
                            for (int index = 0; index < this.SelectedShipList.Count; ++index)
                            {
                                fleet.AddShip(this.SelectedShipList[index].SoftCopy());
                                fleet.Ships[index].RelativeFleetOffset = new Vector2(num5 * (float)index, 0.0f);
                            }
                        }
                        fleet.ProjectPos(this.ProjectedPosition, facing - 1.570796f, fVec2);
                        this.projectedGroup = (ShipGroup)fleet;
                    }
                }
                else
                    this.ProjectingPosition = false;
            }
        }
        /**
            Variant of DoToughNutRequisitionORGI

        */
        private void DoToughNutRequisition()
        {
            float EnemyTroopStr = this.GetEnemyTroopStr();
            float EnemyShipStr = this.GetEnemyStrAtTarget();
            //sorted area of operations by this.empire strength > opposition strength at target
            //  & sorted by nearest distance AO
            IOrderedEnumerable<AO> sorted =
                from ao in this.empire.GetGSAI().AreasOfOperations
                //orderby ao.GetOffensiveForcePool().Sum(bombs => bombs.BombBays.Count) > 0 descending
                orderby ao.GetOffensiveForcePool().Where(combat => !combat.InCombat).Sum(strength => strength.BaseStrength) >= this.MinimumTaskForceStrength descending
                orderby Vector2.Distance(this.AO, ao.Position)
                select ao;

            if (sorted.Count<AO>() == 0)
            {
                return;//a target is unavailable
            }
            //a target is available
            List<Ship> Bombers = new List<Ship>();
            List<Ship> EverythingElse = new List<Ship>();
            List<Troop> Troops = new List<Troop>();
            foreach (AO area in sorted)
            {
                foreach (Ship ship in this.empire.GetShips().OrderBy(str=> str.BaseStrength))
                {
                    if ((ship.Role == "station" || ship.Role == "platform")
                        || ship.BaseStrength == 0f
                        || Vector2.Distance(ship.Center, area.Position) >= area.Radius
                        || ship.InCombat
                        || ship.fleet != null
                        || this.empire.GetGSAI().DefensiveCoordinator.DefensiveForcePool.Contains(ship))//&& ship.fleet.Task == null) //&& ship.fleet != null && ship.fleet.Task == null)
                    {
                        continue;
                    }
                    if (ship.BombBays.Count <= 0)
                    {
                        EverythingElse.Add(ship);
                    }
                    else
                    {
                        Bombers.Add(ship);
                    }
                }
                foreach (Planet p in area.GetPlanets())
                {
                    if (p.RecentCombat || p.ParentSystem.combatTimer>0)
                    {
                        continue;
                    }
                    foreach (Troop t in p.TroopsHere)
                    {
                        if (t.GetOwner() != this.empire)
                        {
                            continue;
                        }
                        Troops.Add(t);
                    }
                }
            }
            List<Ship> TaskForce = new List<Ship>();
            float strAdded = 0f;
            List<Ship>.Enumerator enumerator = EverythingElse.GetEnumerator();
            try
            {
                do
                {
                    if (!enumerator.MoveNext())
                    {
                        break;
                    }
                    Ship ship = enumerator.Current;
                    TaskForce.Add(ship);
                    strAdded = strAdded + ship.GetStrength();
                }
                while (strAdded <= EnemyShipStr * 3f);//1.65f); //Ermenildo V. Castro, Jr. 07/25/15
            }
            finally
            {
                ((IDisposable)enumerator).Dispose();
            }
            List<Ship> BombTaskForce = new List<Ship>();
            int numBombs = 0;
            foreach (Ship ship in Bombers)
            {
                if (numBombs >= 20)
                {
                    continue;
                }
                BombTaskForce.Add(ship);
                numBombs = numBombs + ship.BombBays.Count;
            }
            List<Troop> PotentialTroops = new List<Troop>();
            float troopStr = 0f;
            List<Troop>.Enumerator enumerator1 = Troops.GetEnumerator();
            int numOfTroops =0;
            try
            {
                do
                {
                    if (numOfTroops > 15 || !enumerator1.MoveNext())
                    {
                        break;
                    }
                    numOfTroops++;
                    Troop t = enumerator1.Current;
                    PotentialTroops.Add(t);
                    troopStr = troopStr + (float)t.Strength;
                }
                while (troopStr <= EnemyTroopStr * 3f);//1.25f ); //Ermenildo V. Castro, Jr. 07/25/15
            }
            finally
            {
                ((IDisposable)enumerator1).Dispose();
            }
            if (strAdded > EnemyShipStr * 3f)//1.65f) //Ermenildo V. Castro, Jr. 07/25/15
            {
                if (this.TargetPlanet.Owner == null || this.TargetPlanet.Owner != null && !this.empire.GetRelations().ContainsKey(this.TargetPlanet.Owner))
                {
                    this.EndTask();
                    return;
                }
                if (this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWar)
                {
                    this.empire.GetGSAI().DeclareWarOn(this.TargetPlanet.Owner, this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWarType);
                }
                AO ClosestAO = sorted.First<AO>();
                MilitaryTask assault = new MilitaryTask(this.empire)
                {
                    AO = this.TargetPlanet.Position,
                    AORadius = 75000f,
                    type = MilitaryTask.TaskType.AssaultPlanet
                };
                ClosestAO.GetCoreFleet().Owner.GetGSAI().TasksToAdd.Add(assault);
                assault.WhichFleet = ClosestAO.WhichFleet;
                ClosestAO.GetCoreFleet().Task = assault;
                assault.IsCoreFleetTask = true;
                assault.Step = 1;

                assault.TargetPlanet = this.TargetPlanet;
                ClosestAO.GetCoreFleet().TaskStep = 0;
                ClosestAO.GetCoreFleet().Name = "Doom Fleet";
                foreach (Ship ship in TaskForce)
                {
                    if (ship.fleet != null)
                    {
                        ship.fleet.Ships.Remove(ship);
                    }
                    ship.GetAI().OrderQueue.Clear();
                    this.empire.GetGSAI().DefensiveCoordinator.remove(ship);
                    //foreach (KeyValuePair<SolarSystem, SystemCommander> entry in this.empire.GetGSAI().DefensiveCoordinator.DefenseDict)
                    //{
                    //    List<Ship> toRemove = new List<Ship>();
                    //    foreach (KeyValuePair<Guid, Ship> defender in entry.Value.ShipsDict)
                    //    {
                    //        if (defender.Key != ship.guid)
                    //        {
                    //            continue;
                    //        }
                    //        toRemove.Add(defender.Value);
                    //    }
                    //    foreach (Ship s in toRemove)
                    //    {
                    //        entry.Value.ShipsDict.Remove(s.guid);
                    //    }
                    //}
                    ship.fleet = null;
                }
                foreach (Ship ship in TaskForce)
                {
                    ClosestAO.GetCoreFleet().AddShip(ship);
                }
                foreach (Troop t in PotentialTroops)
                {
                    if (t.GetPlanet() == null)
                    {
                        continue;
                    }
                    (new List<Troop>()).Add(t);
                    Ship launched = t.Launch();
                    ClosestAO.GetCoreFleet().AddShip(launched);
                }
                ClosestAO.GetCoreFleet().AutoArrange();
                if (Bombers.Count > 0 && numBombs > 6)
                {
                    MilitaryTask GlassPlanet = new MilitaryTask(this.empire)
                    {
                        AO = this.TargetPlanet.Position,
                        AORadius = 75000f,
                        type = MilitaryTask.TaskType.GlassPlanet,
                        TargetPlanet = this.TargetPlanet,
                        WaitForCommand = true
                    };

                    Fleet bomberFleet = new Fleet()
                    {
                        Owner = this.empire
                    };
                    bomberFleet.Owner.GetGSAI().TasksToAdd.Add(GlassPlanet);
                    GlassPlanet.WhichFleet = this.empire.GetUnusedKeyForFleet();
                    this.empire.GetFleetsDict().TryAdd(GlassPlanet.WhichFleet, bomberFleet);
                    bomberFleet.Task = GlassPlanet;
                    bomberFleet.Name = "Bomber Fleet";
                    foreach (Ship ship in BombTaskForce)
                    {
                        if (ship.fleet != null)
                        {
                            ship.fleet.Ships.Remove(ship);
                        }
                        ship.GetAI().OrderQueue.Clear();
                        this.empire.GetGSAI().DefensiveCoordinator.remove(ship);
                        //foreach (KeyValuePair<SolarSystem, SystemCommander> entry in this.empire.GetGSAI().DefensiveCoordinator.DefenseDict)
                        //{
                        //    List<Ship> toRemove = new List<Ship>();
                        //    foreach (KeyValuePair<Guid, Ship> defender in entry.Value.ShipsDict)
                        //    {
                        //        if (defender.Key != ship.guid)
                        //        {
                        //            continue;
                        //        }
                        //        toRemove.Add(defender.Value);
                        //    }
                        //    foreach (Ship s in toRemove)
                        //    {
                        //        entry.Value.ShipsDict.Remove(s.guid);
                        //    }
                        //}
                        ship.fleet = null;
                    }
                    foreach (Ship ship in BombTaskForce)
                    {
                        bomberFleet.AddShip(ship);
                    }
                    bomberFleet.AutoArrange();
                }
                this.Step = 1;
                this.empire.GetGSAI().TaskList.QueuePendingRemoval(this);
            }
        }
        /**
            This method allocates any available manpower into a TaskForce for offensive measures; and de-allocates the TaskForce from other fleet contingents.
            Deprecated? --> DOToughtNutRequisition?
        */
        private void DoToughNutRequisitionORIG()
        {
            float EnemyTroopStr = this.GetEnemyTroopStr();
            float EnemyShipStr = this.GetEnemyStrAtTarget();
            //create collection of sorted AOs
            IOrderedEnumerable<Ship_Game.Gameplay.AO> sorted =
                from ao in this.empire.GetGSAI().AreasOfOperations //foreach AO, order by enemy & distance, then "select" for addition into collection
                orderby Vector2.Distance(this.AO, ao.Position)
                select ao;
            //if target is empty, AO's absent, exit method call
            if (sorted.Count<Ship_Game.Gameplay.AO>() == 0)
            {
                return;
            }
            //else, there are targets
            List<Ship> Bombers = new List<Ship>();
            List<Ship> EverythingElse = new List<Ship>();
            List<Troop> Troops = new List<Troop>();
            //calculate this faction's strength
            foreach (Ship_Game.Gameplay.AO area in sorted)
            {
                //claculate opposition fleet strength
                foreach (Ship ship in this.empire.GetShips())
                {
                    //if ship in ships in AO are null, or outside area of operation, or in combat , or in defensive DefensiveForcePool, increment to next ship
                    //(unavilable to be requisitioned for offense)
                    if (ship.GetStrength() == 0f
                        || Vector2.Distance(ship.Center, area.Position) >= area.Radius
                        || ship.InCombat
                        || ship.fleet != null
                        || this.empire.GetGSAI().DefensiveCoordinator.DefensiveForcePool.Contains(ship))// ship.GetAI().SystemToDefend !=null) //&& ship.fleet != null & ship.fleet.Task == null)
                                                                                                        //ships managed by the DefensiveCoordinator or unable to be re-allocated for offense
                    {
                        continue;
                    }
                    //for valid ships in this faction's empire
                    if (ship.BombBays.Count <= 0)
                    {
                        EverythingElse.Add(ship);
                    }
                    else
                    {
                        Bombers.Add(ship);
                    }
                }
                //claculate ground troops that may be allocated for offensive
                foreach (Planet p in area.GetPlanets())
                {
                    if (p.RecentCombat)
                    {
                        continue;
                    }
                    foreach (Troop t in p.TroopsHere)
                    {
                        if (t.GetOwner() != this.empire)
                        {
                            continue;
                        }
                        Troops.Add(t);
                    }
                }
            }
            //determine TaskForce to match calculated opposition strength
            List<Ship> TaskForce = new List<Ship>();
            float strAdded = 0f;
            List<Ship>.Enumerator enumerator = EverythingElse.GetEnumerator(); //enumerator returns position information
            try
            {
                do
                {
                    // Returns:
                    //     true if the enumerator was successfully advanced to the next element; false if
                    //     the enumerator has passed the end of the collection.
                    if (!enumerator.MoveNext())
                    {
                        break;
                    }
                    Ship ship = enumerator.Current;
                    TaskForce.Add(ship); //add ships that are idle (without destination ~ MoveNext)
                    strAdded = strAdded + ship.GetStrength(); //sum the strength of the task force
                }
                while (strAdded <= EnemyShipStr );//* 1.65f); //continue requisitoining ships until TaskForceStrength is greater than EnemyShipStr
            }
            finally
            {
                ((IDisposable)enumerator).Dispose(); //de-allocate object
            }
            List<Ship> BombTaskForce = new List<Ship>();
            int numBombs = 0;
            foreach (Ship ship in Bombers)
            {
                if (numBombs >= 20)
                {
                    continue; //bomber fleet should consist of at max twenth bombers
                }
                BombTaskForce.Add(ship);
                numBombs = numBombs + ship.BombBays.Count;
            }
            List<Troop> PotentialTroops = new List<Troop>();
            float troopStr = 0f;
            List<Troop>.Enumerator enumerator1 = Troops.GetEnumerator();
            int numOfTroops=0;
            try
            {
                do
                {
                    if (!enumerator1.MoveNext())
                    {
                        break;
                    }
                    numOfTroops++;
                    Troop t = enumerator1.Current;
                    PotentialTroops.Add(t);
                    troopStr = troopStr + t.Strength;
                }
                while (troopStr <= EnemyTroopStr * 1.25f || numOfTroops <15 ); //create sufficient ground force for offensive action
            }
            finally
            {
                ((IDisposable)enumerator1).Dispose();
            }
            //if this faction ship strength is greater than opposition 160% of opposition
            //Ermenildo V. Castro, Jr.
            //07/25/15
            //"* 1.65f" --> "* 3f"
            if (strAdded > EnemyShipStr * 3f)//1.65f)
            {
                if (this.TargetPlanet.Owner == null || this.TargetPlanet.Owner != null && !this.empire.GetRelations().ContainsKey(this.TargetPlanet.Owner))
                {
                    this.EndTask();
                    return;
                }
                if (this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWar)
                {
                    this.empire.GetGSAI().DeclareWarOn(this.TargetPlanet.Owner, this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWarType);
                }
                //retrieve closest area of operations target
                Ship_Game.Gameplay.AO ClosestAO = sorted.First<Ship_Game.Gameplay.AO>();
                //create assault MilitaryTask
                MilitaryTask assault = new MilitaryTask(this.empire) //declarative property instantiation, constructor supplement
                {
                    AO = this.TargetPlanet.Position,
                    AORadius = 75000f,
                    type = MilitaryTask.TaskType.AssaultPlanet
                };
                ClosestAO.GetCoreFleet().Owner.GetGSAI().TasksToAdd.Add(assault);
                assault.WhichFleet = ClosestAO.WhichFleet; //assault fleet, WhichFleet, is assigned the fleet closest to target AO
                ClosestAO.GetCoreFleet().Task = assault;
                assault.IsCoreFleetTask = true;
                assault.Step = 1; //Step, used for?
                assault.TargetPlanet = this.TargetPlanet;
                ClosestAO.GetCoreFleet().TaskStep = 0;
                ClosestAO.GetCoreFleet().Name = "Doom Fleet";
                foreach (Ship ship in TaskForce)
                {
                    if (ship.fleet != null)
                    {
                        ship.fleet.Ships.Remove(ship); //remove ship from global empire fleet pool
                    }
                    ship.GetAI().OrderQueue.Clear(); //ship, rescind previous orders
                    this.empire.GetGSAI().DefensiveCoordinator.remove(ship); //remove ship from defensive coordinator pool
                    //foreach (KeyValuePair<SolarSystem, SystemCommander> entry in this.empire.GetGSAI().DefensiveCoordinator.DefenseDict)
                    //{

                    //    List<Ship> toRemove = new List<Ship>();
                    //    foreach (KeyValuePair<Guid, Ship> defender in entry.Value.ShipsDict)
                    //    {
                    //        if (defender.Key != ship.guid)
                    //        {
                    //            continue;
                    //        }
                    //        toRemove.Add(defender.Value);
                    //    }
                    //    foreach (Ship s in toRemove)
                    //    {
                    //        entry.Value.ShipsDict.Remove(s.guid);

                    //    }
                    //}
                    ship.fleet = null; //ship is unassigned to any fleet
                }
                //ASSIGN SHIPS
                foreach (Ship ship in TaskForce)
                {
                    ClosestAO.GetCoreFleet().AddShip(ship); //TaskForce ship is added into the core fleet
                }
                //ASSIGN GROUND TROOPS
                foreach (Troop t in PotentialTroops)
                {
                    if (t.GetPlanet() == null)
                    {
                        continue;
                    }
                    (new List<Troop>()).Add(t);
                    Ship launched = t.Launch(); //launch troop from ground
                    ClosestAO.GetCoreFleet().AddShip(launched); //add troop transport into core fleet
                }
                ClosestAO.GetCoreFleet().AutoArrange();
                //ASSIGN BOMBERS
                if (Bombers.Count > 0 && numBombs > 6)
                {
                    MilitaryTask GlassPlanet = new MilitaryTask(this.empire) //task this empire to glass opposition planet
                    { //multiple properties assignment declaration
                        AO = this.TargetPlanet.Position,//the target planet
                        AORadius = 75000f,
                        type = MilitaryTask.TaskType.GlassPlanet,
                        TargetPlanet = this.TargetPlanet,
                        WaitForCommand = true
                    };
                    Fleet bomberFleet = new Fleet()
                    {
                        Owner = this.empire
                    };
                    bomberFleet.Owner.GetGSAI().TasksToAdd.Add(GlassPlanet);
                    GlassPlanet.WhichFleet = this.empire.GetUnusedKeyForFleet();
                    this.empire.GetFleetsDict().TryAdd(GlassPlanet.WhichFleet, bomberFleet);
                    bomberFleet.Task = GlassPlanet;
                    bomberFleet.Name = "Bomber Fleet";
                    foreach (Ship ship in BombTaskForce)
                    {
                        if (ship.fleet != null)
                        {
                            ship.fleet.Ships.Remove(ship);
                        }
                        ship.GetAI().OrderQueue.Clear();
                        this.empire.GetGSAI().DefensiveCoordinator.remove(ship);

                        ship.fleet = null;
                    }
                    foreach (Ship ship in BombTaskForce)
                    {
                        bomberFleet.AddShip(ship);
                    }
                    bomberFleet.AutoArrange();
                }
                this.Step = 1; //What is step for?
                this.empire.GetGSAI().TaskList.QueuePendingRemoval(this); //remove this MilitaryTask from queue
            }
        }
        private void RequisitionExplorationForcebroke()
        {
            IOrderedEnumerable<Ship_Game.Gameplay.AO> sorted =
                from ao in this.empire.GetGSAI().AreasOfOperations
                orderby Vector2.Distance(this.AO, ao.Position)
                select ao;
            if (sorted.Count<Ship_Game.Gameplay.AO>() == 0)
            {
                return;
            }
            Ship_Game.Gameplay.AO ClosestAO = sorted.First<Ship_Game.Gameplay.AO>();
            this.EnemyStrength = 0f;
            foreach (KeyValuePair<Guid, ThreatMatrix.Pin> pin in this.empire.GetGSAI().ThreatMatrix.Pins)
            {
                if (Vector2.Distance(this.AO, pin.Value.Position) >= this.AORadius || EmpireManager.GetEmpireByName(pin.Value.EmpireName) == this.empire)
                {
                    continue;
                }
                MilitaryTask enemyStrength = this;
                enemyStrength.EnemyStrength = enemyStrength.EnemyStrength + pin.Value.Strength;
            }
            this.MinimumTaskForceStrength = this.EnemyStrength + 0.35f * this.EnemyStrength;
            if (this.MinimumTaskForceStrength == 0f)
            {
                this.MinimumTaskForceStrength = 500f;
            }
            foreach (KeyValuePair<Empire, Relationship> entry in this.empire.GetRelations())
            {
                if (!entry.Value.AtWar || entry.Key.isFaction || this.MinimumTaskForceStrength <= 1000f)
                {
                    continue;
                }
                this.EndTask();
                return;
            }
            List<Ship> PotentialAssaultShips = new List<Ship>();
            List<Troop> PotentialTroops = new List<Troop>();
            foreach (Ship ship in ClosestAO.GetOffensiveForcePool())
            {
                if (ship.fleet != null || (!ship.HasTroopBay && !ship.hasTransporter || ship.TroopList.Count <= 0) && !(ship.Role == "troop") || ship.fleet != null)
                {
                    continue;
                }
                PotentialAssaultShips.Add(ship);
            }
            List<Planet> shipyards = new List<Planet>();
            foreach (Planet planet1 in ClosestAO.GetPlanets())
            {
                if (!planet1.HasShipyard)
                {
                    continue;
                }
                shipyards.Add(planet1);
            }
            IOrderedEnumerable<Planet> planets =
                from p in shipyards
                orderby Vector2.Distance(p.Position, this.TargetPlanet.Position)
                select p;
            if (planets.Count<Planet>() != 0)
            {
                IOrderedEnumerable<Planet> sortedList =
                    from planet in ClosestAO.GetPlanets()
                    orderby Vector2.Distance(planet.Position, planets.First<Planet>().Position)
                    select planet;
                foreach (Planet planet2 in sortedList)
                {
                    foreach (Troop t in planet2.TroopsHere)
                    {
                        if (t.GetOwner() != this.empire)
                        {
                            continue;
                        }
                        t.SetPlanet(planet2);
                        PotentialTroops.Add(t);
                    }
                }
                float ourAvailableStrength = 0f;
                foreach (Ship ship in PotentialAssaultShips)
                {
                    if (ship.fleet != null)
                    {
                        continue;
                    }
                    foreach (Troop t in ship.TroopList)
                    {
                        ourAvailableStrength = ourAvailableStrength + (float)t.Strength;
                    }
                }
                foreach (Troop t in PotentialTroops)
                {
                    ourAvailableStrength = ourAvailableStrength + (float)t.Strength;
                }
                float tfstrength = 0f;
                BatchRemovalCollection<Ship> elTaskForce = new BatchRemovalCollection<Ship>();
                foreach (Ship ship in ClosestAO.GetOffensiveForcePool())
                {
                    if (ship.InCombat || ship.fleet != null || tfstrength >= this.MinimumTaskForceStrength)
                    {
                        continue;
                    }
                    tfstrength = tfstrength + ship.GetStrength();
                    elTaskForce.Add(ship);
                }
                if (tfstrength >= this.MinimumTaskForceStrength && ourAvailableStrength >= 20f)
                {
                    this.TaskForce = elTaskForce;
                    this.StartingStrength = tfstrength;
                    int i = 1;
                    while (i < 10)
                    {
                        if (this.empire.GetGSAI().UsedFleets.Contains(i))
                        {
                            i++;
                        }
                        else
                        {
                            Fleet newFleet = new Fleet();
                            float ForceStrength = 0f;
                            List<Ship>.Enumerator enumerator = PotentialAssaultShips.GetEnumerator();
                            try
                            {
                                do
                                {
                                    if (!enumerator.MoveNext())
                                    {
                                        break;
                                    }
                                    Ship ship = enumerator.Current;
                                    newFleet.AddShip(ship);
                                    foreach (Troop t in ship.TroopList)
                                    {
                                        ForceStrength = ForceStrength + (float)t.Strength;
                                    }
                                }
                                while (ForceStrength < 20f);
                            }
                            finally
                            {
                                ((IDisposable)enumerator).Dispose();
                            }
                            List<Troop>.Enumerator enumerator1 = PotentialTroops.GetEnumerator();
                            try
                            {
                                do
                                {
                                Label1:
                                    if (!enumerator1.MoveNext())
                                    {
                                        break;
                                    }
                                    Troop t = enumerator1.Current;
                                    if (t.GetPlanet() != null)
                                    {
                                        (new List<Troop>()).Add(t);
                                        Ship launched = t.Launch();
                                        ForceStrength = ForceStrength + (float)t.Strength;
                                        newFleet.AddShip(launched);
                                    }
                                    else
                                    {
                                        goto Label1;
                                    }
                                }
                                while (ForceStrength < 20f);
                            }
                            finally
                            {
                                ((IDisposable)enumerator1).Dispose();
                            }
                            foreach (Ship ship in this.TaskForce)
                            {
                                ship.GetAI().OrderQueue.Clear();
                                ship.GetAI().State = AIState.AwaitingOrders;
                                newFleet.AddShip(ship);
                                ClosestAO.GetOffensiveForcePool().Remove(ship);
                                ClosestAO.GetWaitingShips().Remove(ship);

                            }
                            newFleet.Owner = this.empire;
                            newFleet.Name = "Exploration Force";
                            newFleet.AutoArrange();
                            this.empire.GetFleetsDict()[i] = newFleet;
                            this.empire.GetGSAI().UsedFleets.Add(i);
                            this.WhichFleet = i;
                            newFleet.Task = this;
                            break;
                        }
                    }
                    this.Step = 1;
                }
                return;
            }
            this.EndTask();
        }
        private void RequisitionDefenseForce()
        {
            float forcePoolStr = 0f;
            float tfstrength = 0f;
            BatchRemovalCollection<Ship> elTaskForce = new BatchRemovalCollection<Ship>();
            forcePoolStr = this.empire.GetForcePoolStrength();

            foreach (Ship ship in this.empire.GetForcePool().OrderBy(strength=> strength.GetStrength()))
            {
                if (ship.fleet != null)
                {
                    continue;
                }
                if (tfstrength >= forcePoolStr / 2f)
                {
                    break;
                }
                if (ship.GetStrength() <= 0f || ship.InCombat)
                {
                    continue;
                }
                elTaskForce.Add(ship);
                tfstrength = tfstrength + ship.GetStrength();
            }
            this.TaskForce = elTaskForce;
            this.StartingStrength = tfstrength;
            int i = 1;
            while (i < 10)
            {
                if (this.empire.GetGSAI().UsedFleets.Contains(i))
                {
                    i++;
                }
                else
                {
                    Fleet newFleet = new Fleet();
                    foreach (Ship ship in this.TaskForce)
                    {
                        newFleet.AddShip(ship);
                    }
                    newFleet.Owner = this.empire;
                    newFleet.Name = "Defensive Fleet";
                    newFleet.AutoArrange();
                    this.empire.GetFleetsDict()[i] = newFleet;
                    this.empire.GetGSAI().UsedFleets.Add(i);
                    this.WhichFleet = i;
                    newFleet.Task = this;
                    List<Ship>.Enumerator enumerator = this.TaskForce.GetEnumerator();
                    try
                    {
                        while (enumerator.MoveNext())
                        {
                            Ship ship = enumerator.Current;
                            this.empire.ForcePoolRemove(ship);
                        }
                        break;
                    }
                    finally
                    {
                        ((IDisposable)enumerator).Dispose();
                    }
                }
            }
            this.Step = 1;
        }
 private void RequisitionClaimForceORIG()
 {
     IOrderedEnumerable<Ship_Game.Gameplay.AO> sorted =
         from ao in this.empire.GetGSAI().AreasOfOperations
         orderby ao.GetOffensiveForcePool().Sum(strength => strength.GetStrength()) >= this.MinimumTaskForceStrength
         orderby Vector2.Distance(this.AO, ao.Position)
         select ao;
     if (sorted.Count<Ship_Game.Gameplay.AO>() == 0)
     {
         return;
     }
     Ship_Game.Gameplay.AO ClosestAO = sorted.First<Ship_Game.Gameplay.AO>();
     float tfstrength = 0f;
     BatchRemovalCollection<Ship> elTaskForce = new BatchRemovalCollection<Ship>();
     int shipCount = 0;
     foreach (Ship ship in ClosestAO.GetOffensiveForcePool())
     {
         if (tfstrength >= 500f && shipCount >= 3)
         {
             break;
         }
         if (ship.GetStrength() <= 0f || ship.InCombat || ship.fleet != null)
         {
             continue;
         }
         shipCount++;
         elTaskForce.Add(ship);
         tfstrength = tfstrength + ship.GetStrength();
     }
     if (shipCount < 3 || tfstrength < 500f)
     {
         return;
     }
     this.TaskForce = elTaskForce;
     this.StartingStrength = tfstrength;
     int i = 1;
     while (i < 10)
     {
         if (this.empire.GetGSAI().UsedFleets.Contains(i))
         {
             i++;
         }
         else
         {
             Fleet newFleet = new Fleet();
             foreach (Ship ship in this.TaskForce)
             {
                 newFleet.AddShip(ship);
             }
             newFleet.Owner = this.empire;
             newFleet.Name = "Scout Fleet";
             newFleet.AutoArrange();
             this.empire.GetFleetsDict()[i] = newFleet;
             this.empire.GetGSAI().UsedFleets.Add(i);
             this.WhichFleet = i;
             newFleet.Task = this;
             List<Ship>.Enumerator enumerator = this.TaskForce.GetEnumerator();
             try
             {
                 while (enumerator.MoveNext())
                 {
                     Ship ship = enumerator.Current;
                     ClosestAO.GetOffensiveForcePool().Remove(ship);
                     ClosestAO.GetWaitingShips().Remove(ship);
                 }
                 break;
             }
             finally
             {
                 ((IDisposable)enumerator).Dispose();
             }
         }
     }
     this.Step = 1;
 }
        //added by gremlin assaultrequistion forces
        private void RequisitionAssaultForcesDevek()
        {
            List<Troop>.Enumerator enumerator;
            if (this.IsToughNut)
            {
                this.DoToughNutRequisition();
                return;
            }
            IOrderedEnumerable<AO> sorted =
                from ao in this.empire.GetGSAI().AreasOfOperations
                orderby Vector2.Distance(this.AO, ao.Position)
                select ao;
            if (sorted.Count<AO>() == 0)
            {
                return;
            }
            AO ClosestAO = sorted.First<AO>();
            if (this.TargetPlanet.Owner == null || !this.empire.GetRelations().ContainsKey(this.TargetPlanet.Owner))
            {
                this.EndTask();
                return;
            }
            if (this.empire.GetRelations()[this.TargetPlanet.Owner].Treaty_Peace)
            {
                this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWar = false;
                this.EndTask();
                return;
            }
            float EnemyTroopStrength = this.TargetPlanet.GetGroundStrengthOther(this.empire);
            //this.TargetPlanet.GetGroundStrengthOther(this.empire);
            //foreach (PlanetGridSquare pgs in this.TargetPlanet.TilesList)
            //{

            //    if (pgs.TroopsHere.Count <= 0)
            //    {
            //        if (pgs.building == null || pgs.building.CombatStrength <= 0)
            //        {
            //            continue;
            //        }
            //        EnemyTroopStrength = EnemyTroopStrength + (float)(pgs.building.CombatStrength + 5);
            //    }
            //    else if(pgs.TroopsHere[0].GetOwner() != this.empire)
            //    {
            //        EnemyTroopStrength = EnemyTroopStrength + (float)pgs.TroopsHere[0].Strength;
            //    }
            //}
            if (EnemyTroopStrength < 20f)
            {
                EnemyTroopStrength = 25f;
            }

            List<Ship> PotentialAssaultShips = new List<Ship>();
            List<Troop> PotentialTroops = new List<Troop>();
            List<Ship> PotentialBombers = new List<Ship>();
            //added by gremlin trying to get AI to use ships with assault bays.
            foreach (Ship ship in ClosestAO.GetOffensiveForcePool())
            {
                if ((!ship.HasTroopBay || ship.TroopList.Count <= 0) && !(ship.Role == "troop") || ship.fleet != null)
                {
                    if (!ship.HasTroopBay && !ship.hasTransporter || ship.TroopList.Count == 0 || ship.fleet == null)
                    {
                        continue;
                    }
                }
                PotentialAssaultShips.Add(ship);
            }
            List<Planet> shipyards = new List<Planet>();
            foreach (Planet planet1 in ClosestAO.GetPlanets())
            {
                if (!planet1.HasShipyard)
                {
                    continue;
                }
                shipyards.Add(planet1);
            }
            IOrderedEnumerable<Planet> planets =
                from p in shipyards
                orderby Vector2.Distance(p.Position, this.TargetPlanet.Position)
                select p;
            if (planets.Count<Planet>() == 0)
            {
                return;
            }
            IOrderedEnumerable<Planet> sortedList =
                from planet in ClosestAO.GetPlanets()
                orderby Vector2.Distance(planet.Position, planets.First<Planet>().Position)
                select planet;
            foreach (Planet planet2 in sortedList)
            {
                foreach (Troop t in planet2.TroopsHere)
                {
                    if (t.GetOwner() != this.empire || planet2.ParentSystem.combatTimer >0)
                    {
                        continue;
                    }
                    t.SetPlanet(planet2);
                    PotentialTroops.Add(t);
                }
            }
            float ourAvailableStrength = 0f;
            foreach (Ship ship in PotentialAssaultShips)
            {
                foreach (Troop t in ship.TroopList)
                {
                    ourAvailableStrength = ourAvailableStrength + (float)t.Strength;
                }
            }

            bool GoodToGo = false;
            foreach (Troop t in PotentialTroops)
            {
                ourAvailableStrength = ourAvailableStrength + (float)t.Strength;
            }
            float MinimumEscortStrength = 0f;
            int count = 0;
            float OurPresentStrength = 0f;
            foreach (Ship ship in this.TargetPlanet.system.ShipList)
            {
                if (ship.loyalty == this.TargetPlanet.Owner)
                {
                    MinimumEscortStrength = MinimumEscortStrength + ship.GetStrength();
                    count++;
                }
                if (ship.loyalty != this.empire)
                {
                    continue;
                }
                OurPresentStrength = OurPresentStrength + ship.GetStrength();
            }
            MinimumEscortStrength = MinimumEscortStrength + 0.4f * MinimumEscortStrength +EnemyTroopStrength ;

            this.MinimumTaskForceStrength = MinimumEscortStrength;
            BatchRemovalCollection<Ship> elTaskForce = new BatchRemovalCollection<Ship>();
            float tfstrength = 0f;
            foreach (Ship ship in ClosestAO.GetOffensiveForcePool())
            {
                if (ship.InCombat || ship.fleet != null || (ship.Role == "station" || ship.Role == "platform") || tfstrength >= MinimumEscortStrength || ship.GetStrength() <= 0f)
                {
                    continue;
                }
                tfstrength = tfstrength + ship.GetStrength();
                elTaskForce.Add(ship);
            }
            //&& this.TargetPlanet.GetGroundLandingSpots() <this.TargetPlanet.GetPotentialGroundTroops(this.empire) *.5 )
            if (ourAvailableStrength > EnemyTroopStrength * 1.65f && this.TargetPlanet.GetGroundLandingSpots() >5 && tfstrength >= this.MinimumTaskForceStrength)
            {
                if (this.TargetPlanet.Owner == null || this.TargetPlanet.Owner != null && !this.empire.GetRelations().ContainsKey(this.TargetPlanet.Owner))
                {
                    this.EndTask();
                    return;
                }
                if (this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWar)
                {
                    this.empire.GetGSAI().DeclareWarOn(this.TargetPlanet.Owner, this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWarType);
                }
                GoodToGo = true;
                Fleet newFleet = new Fleet()
                {
                    Owner = this.empire,
                    Name = "Invasion Fleet"
                };
                int i = 1;
                while (i < 10)
                {
                    if (this.empire.GetGSAI().UsedFleets.Contains(i))
                    {
                        i++;
                    }
                    else
                    {
                        float ForceStrength = 0f;
                        List<Ship>.Enumerator enumerator1 = PotentialAssaultShips.GetEnumerator();
                        try
                        {
                            do
                            {
                                if (!enumerator1.MoveNext())
                                {
                                    break;
                                }
                                Ship ship = enumerator1.Current;
                                newFleet.AddShip(ship);
                                foreach (Troop t in ship.TroopList)
                                {
                                    ForceStrength = ForceStrength + (float)t.Strength;
                                }
                            }
                            while (ForceStrength <= EnemyTroopStrength * 2f);
                        }
                        finally
                        {
                            ((IDisposable)enumerator1).Dispose();
                        }
                        List<Troop>.Enumerator enumerator2 = PotentialTroops.GetEnumerator();
                        try
                        {
                            do
                            {
                            Label1:
                                if (!enumerator2.MoveNext())
                                {
                                    break;
                                }
                                Troop t = enumerator2.Current;
                                if (t.GetPlanet() != null)
                                {
                                    (new List<Troop>()).Add(t);
                                    if (t.GetOwner() != null)
                                    {
                                        newFleet.AddShip(t.Launch());
                                        ForceStrength = ForceStrength + (float)t.Strength;
                                    }
                                    else
                                    {
                                        goto Label1;
                                    }
                                }
                                else
                                {
                                    goto Label1;
                                }
                            }
                            while (ForceStrength <= EnemyTroopStrength + EnemyTroopStrength * 0.3f);
                        }
                        finally
                        {
                            ((IDisposable)enumerator2).Dispose();
                        }
                        this.empire.GetFleetsDict()[i] = newFleet;
                        this.empire.GetGSAI().UsedFleets.Add(i);
                        this.WhichFleet = i;
                        newFleet.Task = this;
                        foreach (Ship ship in elTaskForce)
                        {
                            newFleet.AddShip(ship);
                            ship.GetAI().OrderQueue.Clear();
                            ship.GetAI().State = AIState.AwaitingOrders;
                            ClosestAO.GetOffensiveForcePool().Remove(ship);
                            ClosestAO.GetWaitingShips().Remove(ship);
                        }
                        newFleet.AutoArrange();
                        break;
                    }
                }
                this.Step = 1;
            }
            else if (ourAvailableStrength >= EnemyTroopStrength && tfstrength >= this.MinimumTaskForceStrength)
            {
                foreach (Ship ship in ClosestAO.GetOffensiveForcePool())
                {
                    if ((ship.Role == "station" || ship.Role == "platform") || ship.BombBays.Count <= 0)
                    {
                        continue;
                    }
                    PotentialBombers.Add(ship);
                    if (elTaskForce.Contains(ship))
                    {
                        continue;
                    }
                    elTaskForce.Add(ship);
                }
                if (PotentialBombers.Count > 0)
                {
                    if (this.TargetPlanet.Owner == null || this.TargetPlanet.Owner != null && !this.empire.GetRelations().ContainsKey(this.TargetPlanet.Owner))
                    {
                        this.EndTask();
                        return;
                    }
                    if (this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWar)
                    {
                        this.empire.GetGSAI().DeclareWarOn(this.TargetPlanet.Owner, this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWarType);
                    }
                    GoodToGo = true;
                    Fleet newFleet = new Fleet()
                    {
                        Owner = this.empire,
                        Name = "Invasion Fleet"
                    };
                    int i = 1;
                    while (i < 10)
                    {
                        if (this.empire.GetGSAI().UsedFleets.Contains(i))
                        {
                            i++;
                        }
                        else
                        {
                            float ForceStrength = 0f;
                            List<Ship>.Enumerator enumerator3 = PotentialAssaultShips.GetEnumerator();
                            try
                            {
                                do
                                {
                                    if (!enumerator3.MoveNext())
                                    {
                                        break;
                                    }
                                    Ship ship = enumerator3.Current;
                                    newFleet.AddShip(ship);
                                    foreach (Troop t in ship.TroopList)
                                    {
                                        ForceStrength = ForceStrength + (float)t.Strength;
                                    }
                                }
                                while (ForceStrength <= EnemyTroopStrength * 2f);
                            }
                            finally
                            {
                                ((IDisposable)enumerator3).Dispose();
                            }
                            enumerator = PotentialTroops.GetEnumerator();
                            try
                            {
                                do
                                {
                                Label0:
                                    if (!enumerator.MoveNext())
                                    {
                                        break;
                                    }
                                    Troop t = enumerator.Current;
                                    if (t.GetPlanet() != null && t != null)
                                    {
                                        (new List<Troop>()).Add(t);
                                        Ship launched = t.Launch();
                                        ForceStrength = ForceStrength + (float)t.Strength;
                                        newFleet.AddShip(launched);
                                    }
                                    else
                                    {
                                        goto Label0;
                                    }
                                }
                                while (ForceStrength <= EnemyTroopStrength + EnemyTroopStrength * 0.3f);
                            }
                            finally
                            {
                                ((IDisposable)enumerator).Dispose();
                            }
                            this.empire.GetFleetsDict()[i] = newFleet;
                            this.empire.GetGSAI().UsedFleets.Add(i);
                            this.WhichFleet = i;
                            newFleet.Task = this;
                            foreach (Ship ship in elTaskForce)
                            {
                                newFleet.AddShip(ship);
                                ship.GetAI().OrderQueue.Clear();
                                ship.GetAI().State = AIState.AwaitingOrders;
                                ClosestAO.GetOffensiveForcePool().Remove(ship);
                                ClosestAO.GetWaitingShips().Remove(ship);
                            }
                            newFleet.AutoArrange();
                            break;
                        }
                    }
                    this.Step = 1;
                }
            }
            else if (ourAvailableStrength > EnemyTroopStrength * 1.5f)
            {
                if (this.TargetPlanet.Owner == null || this.TargetPlanet.Owner != null && !this.empire.GetRelations().ContainsKey(this.TargetPlanet.Owner))
                {
                    this.EndTask();
                    return;
                }
                if (ClosestAO.GetCoreFleet().Task == null && ClosestAO.GetCoreFleet().GetStrength() > this.MinimumTaskForceStrength)
                {
                    MilitaryTask clearArea = new MilitaryTask(ClosestAO.GetCoreFleet().Owner)
                    {
                        AO = this.TargetPlanet.Position,
                        AORadius = 75000f,
                        type = MilitaryTask.TaskType.ClearAreaOfEnemies
                    };
                    ClosestAO.GetCoreFleet().Owner.GetGSAI().TasksToAdd.Add(clearArea);
                    clearArea.WhichFleet = ClosestAO.WhichFleet;
                    ClosestAO.GetCoreFleet().Task = clearArea;
                    clearArea.IsCoreFleetTask = true;
                    ClosestAO.GetCoreFleet().TaskStep = 1;
                    clearArea.Step = 1;
                    if (this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWar)
                    {
                        this.empire.GetGSAI().DeclareWarOn(this.TargetPlanet.Owner, this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWarType);
                    }
                }
            }
            else if (EnemyTroopStrength > 100f)
            {
                this.IsToughNut = true;
            }
            if (!GoodToGo)
            {
                this.NeededTroopStrength = (int)(EnemyTroopStrength + EnemyTroopStrength * 0.3f - ourAvailableStrength);

            }
        }
        private void RequisitionAssaultForces()
        {
            List<Troop>.Enumerator enumerator;
            if (this.IsToughNut)
            {
                this.DoToughNutRequisition();
                return;
            }
            IOrderedEnumerable<Ship_Game.Gameplay.AO> sorted =
                from ao in this.empire.GetGSAI().AreasOfOperations
                //orderby ao.GetOffensiveForcePool().Sum(bombs => bombs.BombBays.Count) > 0 descending
                //orderby ao.GetOffensiveForcePool().Sum(strength => strength.GetStrength()) >= this.MinimumTaskForceStrength descending
                orderby Vector2.Distance(this.AO, ao.Position)
                select ao;
            //IOrderedEnumerable<Ship_Game.Gameplay.AO> sorted = this.empire.GetGSAI().AreasOfOperations
            //    .OrderByDescending(ao => ao.GetOffensiveForcePool().Sum(bombs => bombs.BombBays.Count) > 0)
            //    .ThenByDescending(ao => ao.GetOffensiveForcePool().Sum(strength => strength.GetStrength()) >= this.MinimumTaskForceStrength)
            //    .ThenBy(ao => Vector2.Distance(this.AO, ao.Position));
            if (sorted.Count<Ship_Game.Gameplay.AO>() == 0)
            {
                return;
            }
            Ship_Game.Gameplay.AO ClosestAO = sorted.First<Ship_Game.Gameplay.AO>();
            if (this.TargetPlanet.Owner == null || !this.empire.GetRelations().ContainsKey(this.TargetPlanet.Owner))
            {
                this.EndTask();
                return;
            }
            if (this.empire.GetRelations()[this.TargetPlanet.Owner].Treaty_Peace)
            {
                this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWar = false;
                this.EndTask();
                return;
            }
            float EnemyTroopStrength = 0f;
            int troopCount = 0;
            foreach (PlanetGridSquare pgs in this.TargetPlanet.TilesList)
            {
                if (troopCount > 25)
                    break;
                if (pgs.TroopsHere.Count <= 0)
                {
                    if (pgs.building == null || pgs.building.CombatStrength <= 0)
                    {
                        continue;
                    }
                    EnemyTroopStrength = EnemyTroopStrength + (float)(pgs.building.Strength + (float)(pgs.building.CombatStrength));
                    troopCount++;
                }
                else
                {
                    troopCount++;
                    EnemyTroopStrength = EnemyTroopStrength + (float)pgs.TroopsHere[0].Strength;
                    if (pgs.building == null || pgs.building.CombatStrength <= 0)
                    {
                        continue;
                    }
                    EnemyTroopStrength = EnemyTroopStrength + (float)(pgs.building.Strength + (float)(pgs.building.CombatStrength));
                }
            }

            if (EnemyTroopStrength < 80f)
            {
                EnemyTroopStrength = 80f;
            }
            EnemyTroopStrength *= (1.2f + (int)Ship.universeScreen.GameDifficulty * .1f);
            List<Ship> PotentialAssaultShips = new List<Ship>();
            List<Troop> PotentialTroops = new List<Troop>();
            List<Ship> PotentialBombers = new List<Ship>();
            foreach (Ship ship in this.empire.GetShips().OrderBy(troops => Vector2.Distance(this.AO, troops.Position)))
            {
                if ((ship.TroopList.Count <= 0 || ship.fleet != null) || (!ship.HasTroopBay && ship.Role != "troop" && !ship.hasTransporter))
                {
                    continue;
                }
                PotentialAssaultShips.Add(ship);
            }
            List<Planet> shipyards = new List<Planet>();
            foreach (Planet planet1 in ClosestAO.GetPlanets())
            {
                if (!planet1.HasShipyard)
                {
                    continue;
                }
                shipyards.Add(planet1);
            }
            IOrderedEnumerable<Planet> planets =
                from p in shipyards
                orderby Vector2.Distance(p.Position, this.TargetPlanet.Position)
                select p;
            if (planets.Count<Planet>() == 0)
            {
                return;
            }
            IOrderedEnumerable<Planet> sortedList =
                //from planet in ClosestAO.GetPlanets()
                from planet in empire.GetPlanets()
                //where planet.system.CombatInSystem ==false
                orderby empire.GetGSAI().DefensiveCoordinator.DefenseDict[planet.ParentSystem].ValueToUs *.1f
                orderby Vector2.Distance(planet.Position, planets.First<Planet>().Position)
                select planet;
            //        IOrderedEnumerable<SolarSystem> sortedSystems =
            //from system in systems
            //orderby this.DefenseDict[system].ValueToUs descending
            //orderby Vector2.Distance(system.Position, ship4.Center)
            //select system;

            //foreach(SolarSystem system in this.empire.GetOwnedSystems())
            //{

            //}
            foreach (Planet planet2 in sortedList)
            {
                foreach (Troop t in planet2.TroopsHere)
                {
                    if (t.GetOwner() != this.empire)
                    {
                        continue;
                    }
                    t.SetPlanet(planet2);
                    PotentialTroops.Add(t);
                }
            }
            float ourAvailableStrength = 0f;
            foreach (Ship ship in PotentialAssaultShips)
            {
                foreach (Troop t in ship.TroopList)
                {
                    ourAvailableStrength = ourAvailableStrength + (float)t.Strength;
                }
            }
            bool GoodToGo = false;
            foreach (Troop t in PotentialTroops)
            {
                ourAvailableStrength = ourAvailableStrength + (float)t.Strength;
            }
            float MinimumEscortStrength = 0f;
            int count = 0;
            float OurPresentStrength = 0f;
            foreach (Ship ship in this.TargetPlanet.system.ShipList)
            {
                if (ship.loyalty == this.TargetPlanet.Owner)
                {
                    MinimumEscortStrength = MinimumEscortStrength + ship.GetStrength();
                    count++;
                }
                if (ship.loyalty != this.empire)
                {
                    continue;
                }
                OurPresentStrength = OurPresentStrength + ship.GetStrength();
            }
            MinimumEscortStrength *= (1.3f + (int)Ship.universeScreen.GameDifficulty * .1f);
            // I'm unsure on ball-park figures for ship strengths. Given it used to build up to 1500, sticking flat +300 on seems a good start
            //updated. Now it will use 1/10th of the current military strength escort strength needed is under 1000
            if (MinimumEscortStrength < 1000)
                MinimumEscortStrength = this.empire.currentMilitaryStrength * .10f;
            //if (MinimumEscortStrength + OurPresentStrength < this.empire.MilitaryScore *.1f) //+1500
            //{
            //    MinimumEscortStrength = this.empire.MilitaryScore * .15f - OurPresentStrength; //1500f - OurPresentStrength;
            //}
            //if (MinimumEscortStrength < this.empire.MilitaryScore * .15f)
            //{
            //    MinimumEscortStrength = this.empire.MilitaryScore * .15f;
            //}
            this.MinimumTaskForceStrength = MinimumEscortStrength;
            BatchRemovalCollection<Ship> elTaskForce = new BatchRemovalCollection<Ship>();
            float tfstrength = 0f;

            foreach (Ship ship in ClosestAO.GetOffensiveForcePool())
            {
                if (ship.InCombat || ship.fleet != null || tfstrength >= MinimumEscortStrength
                    || ship.GetAI().State == AIState.Explore
                    || ship.GetStrength() <= 0f ||(ship.Role == "station" || ship.Role == "platform") )
                {
                    continue;
                }
                tfstrength = tfstrength + ship.GetStrength();
                elTaskForce.Add(ship);
            }
            if (!this.empire.isFaction
                && this.empire.data.DiplomaticPersonality.Name == "Aggressive"
                //|| empire.data.DiplomaticPersonality.Name == "Xenophobic"
                //|| empire.GetRelations().Where(war => war.Value.ActiveWar !=null).Count() <2
                )
            {
                if(!this.IsCoreFleetTask)
                foreach (KeyValuePair<SolarSystem, SystemCommander> entry in this.empire.GetGSAI().DefensiveCoordinator.DefenseDict
                    .OrderByDescending(system => system.Key.CombatInSystem)
                    .ThenByDescending(ship => (ship.Value.GetOurStrength() - ship.Value.IdealShipStrength) < 1000)
                    .ThenByDescending(system => Vector2.Distance(system.Key.Position, this.TargetPlanet.Position))

            )
                {
                    foreach (Ship ship in entry.Value.GetShipList())
                    {
                        if (ship.InCombat || ship.fleet != null || tfstrength >= MinimumEscortStrength || ship.GetStrength() <= 0f)
                        {
                            continue;
                        }
                        tfstrength = tfstrength + ship.GetStrength();
                        elTaskForce.Add(ship);
                    }

                }
            }

            //if (ourAvailableStrength > EnemyTroopStrength * 1.65f && tfstrength >= this.MinimumTaskForceStrength)
            if (this.TargetPlanet.GetGroundLandingSpots() >5 && tfstrength >= this.MinimumTaskForceStrength)
            {
                if (this.TargetPlanet.Owner == null || this.TargetPlanet.Owner != null && !this.empire.GetRelations().ContainsKey(this.TargetPlanet.Owner))
                {
                    this.EndTask();
                    return;
                }
                if (this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWar)
                {
                    this.empire.GetGSAI().DeclareWarOn(this.TargetPlanet.Owner, this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWarType);
                }
                GoodToGo = true;
                Fleet newFleet = new Fleet()
                {
                    Owner = this.empire,
                    Name = "Invasion Fleet"
                };
                int i = 1;
                while (i < 10)
                {
                    if (this.empire.GetGSAI().UsedFleets.Contains(i))
                    {
                        i++;
                    }
                    else
                    {
                        float ForceStrength = 0f;
                        List<Ship>.Enumerator enumerator1 = PotentialAssaultShips.GetEnumerator();
                        try
                        {
                            do
                            {
                                if (!enumerator1.MoveNext())
                                {
                                    break;
                                }
                                Ship ship = enumerator1.Current;
                                newFleet.AddShip(ship);
                                foreach (Troop t in ship.TroopList)
                                {
                                    ForceStrength = ForceStrength + (float)t.Strength;
                                }
                                this.empire.GetGSAI().DefensiveCoordinator.remove(ship);
                            }
                            while (ForceStrength <= EnemyTroopStrength);//* 2f);
                        }
                        finally
                        {
                            ((IDisposable)enumerator1).Dispose();
                        }
                        List<Troop>.Enumerator enumerator2 = PotentialTroops.GetEnumerator();
                        try
                        {
                            do
                            {
                            Label1:
                                if (!enumerator2.MoveNext())
                                {
                                    break;
                                }
                                Troop t = enumerator2.Current;
                                if (t.GetPlanet() != null && t.GetPlanet().ParentSystem.combatTimer <= 0 && !t.GetPlanet().RecentCombat && t.GetPlanet().TroopsHere.Count > t.GetPlanet().developmentLevel)
                                {
                                    (new List<Troop>()).Add(t);
                                    if (t.GetOwner() != null)
                                    {
                                        newFleet.AddShip(t.Launch());
                                        ForceStrength = ForceStrength + (float)t.Strength;

                                    }
                                    else
                                    {
                                        goto Label1;
                                    }
                                }
                                else
                                {
                                    goto Label1;
                                }
                            }
                            while (ForceStrength <= EnemyTroopStrength || ForceStrength <50);//+ EnemyTroopStrength * 0.3f);
                        }
                        finally
                        {
                            ((IDisposable)enumerator2).Dispose();
                        }
                        this.empire.GetFleetsDict()[i] = newFleet;
                        this.empire.GetGSAI().UsedFleets.Add(i);
                        this.WhichFleet = i;
                        newFleet.Task = this;
                        foreach (Ship ship in elTaskForce)
                        {
                            newFleet.AddShip(ship);
                            ship.GetAI().OrderQueue.Clear();
                            ship.GetAI().State = AIState.AwaitingOrders;
                            ClosestAO.GetOffensiveForcePool().Remove(ship);
                            ClosestAO.GetWaitingShips().Remove(ship);
                            this.empire.GetGSAI().DefensiveCoordinator.remove(ship);
                        }
                        newFleet.AutoArrange();
                        break;
                    }
                }
                this.Step = 1;
            }
            else if (ourAvailableStrength >= EnemyTroopStrength && tfstrength >= this.MinimumTaskForceStrength)
            {
                foreach (Ship ship in ClosestAO.GetOffensiveForcePool())
                {
                    if (ship.BombBays.Count <= 0)
                    {
                        continue;
                    }
                    PotentialBombers.Add(ship);
                    if (elTaskForce.Contains(ship))
                    {
                        continue;
                    }
                    elTaskForce.Add(ship);
                }
                if (PotentialBombers.Count > 0)
                {
                    if (this.TargetPlanet.Owner == null || this.TargetPlanet.Owner != null && !this.empire.GetRelations().ContainsKey(this.TargetPlanet.Owner))
                    {
                        this.EndTask();
                        return;
                    }
                    if (this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWar)
                    {
                        this.empire.GetGSAI().DeclareWarOn(this.TargetPlanet.Owner, this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWarType);
                    }
                    GoodToGo = true;
                    Fleet newFleet = new Fleet()
                    {
                        Owner = this.empire,
                        Name = "Invasion Fleet"
                    };
                    int i = 1;
                    while (i < 10)
                    {
                        if (this.empire.GetGSAI().UsedFleets.Contains(i))
                        {
                            i++;
                        }
                        else
                        {
                            float ForceStrength = 0f;
                            List<Ship>.Enumerator enumerator3 = PotentialAssaultShips.GetEnumerator();
                            try
                            {
                                do
                                {
                                    if (!enumerator3.MoveNext())
                                    {
                                        break;
                                    }
                                    Ship ship = enumerator3.Current;
                                    newFleet.AddShip(ship);
                                    foreach (Troop t in ship.TroopList)
                                    {
                                        ForceStrength = ForceStrength + (float)t.Strength;
                                    }
                                }
                                while (ForceStrength <= EnemyTroopStrength * 2f);
                            }
                            finally
                            {
                                ((IDisposable)enumerator3).Dispose();
                            }
                            enumerator = PotentialTroops.GetEnumerator();
                            try
                            {
                                do
                                {
                                Label0:
                                    if (!enumerator.MoveNext())
                                    {
                                        break;
                                    }
                                    Troop t = enumerator.Current;
                                    if (t.GetPlanet() != null && t != null)
                                    {
                                        (new List<Troop>()).Add(t);
                                        Ship launched = t.Launch();
                                        ForceStrength = ForceStrength + (float)t.Strength;
                                        newFleet.AddShip(launched);
                                    }
                                    else
                                    {
                                        goto Label0;
                                    }
                                }
                                while (ForceStrength <= EnemyTroopStrength + EnemyTroopStrength * 0.3f);
                            }
                            finally
                            {
                                ((IDisposable)enumerator).Dispose();
                            }
                            this.empire.GetFleetsDict()[i] = newFleet;
                            this.empire.GetGSAI().UsedFleets.Add(i);
                            this.WhichFleet = i;
                            newFleet.Task = this;
                            foreach (Ship ship in elTaskForce)
                            {
                                newFleet.AddShip(ship);
                                ship.GetAI().OrderQueue.Clear();
                                ship.GetAI().State = AIState.AwaitingOrders;
                                ClosestAO.GetOffensiveForcePool().Remove(ship);
                                ClosestAO.GetWaitingShips().Remove(ship);
                                this.empire.GetGSAI().DefensiveCoordinator.remove(ship);
                            }
                            newFleet.AutoArrange();
                            break;
                        }
                    }
                    this.Step = 1;
                }
            }
            else if (ourAvailableStrength > EnemyTroopStrength )
            {
                if (this.TargetPlanet.Owner == null || this.TargetPlanet.Owner != null && !this.empire.GetRelations().ContainsKey(this.TargetPlanet.Owner))
                {
                    this.EndTask();
                    return;
                }
                if (ClosestAO.GetCoreFleet().Task == null && ClosestAO.GetCoreFleet().GetStrength() > this.MinimumTaskForceStrength)
                {
                    MilitaryTask clearArea = new MilitaryTask(ClosestAO.GetCoreFleet().Owner)
                    {
                        AO = this.TargetPlanet.Position,
                        AORadius = 75000f,
                        type = MilitaryTask.TaskType.ClearAreaOfEnemies
                    };
                    ClosestAO.GetCoreFleet().Owner.GetGSAI().TasksToAdd.Add(clearArea);
                    clearArea.WhichFleet = ClosestAO.WhichFleet;
                    ClosestAO.GetCoreFleet().Task = clearArea;
                    clearArea.IsCoreFleetTask = true;
                    ClosestAO.GetCoreFleet().TaskStep = 1;
                    clearArea.Step = 1;
                    if (this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWar)
                    {
                        this.empire.GetGSAI().DeclareWarOn(this.TargetPlanet.Owner, this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWarType);
                    }
                }
            }
            //else if (EnemyTroopStrength > 100f)
            else if (this.TargetPlanet.GetGroundLandingSpots()<10)
            {
                this.IsToughNut = true;
            }
            if (!GoodToGo)
            {
                this.NeededTroopStrength = (int)(EnemyTroopStrength  - ourAvailableStrength);
            }
        }