private void RunInfrastructurePlanner()
        {
            //if (this.empire.SpaceRoadsList.Sum(node=> node.NumberOfProjectors) < ShipCountLimit * GlobalStats.spaceroadlimit)
            float sspBudget = this.empire.Money * (.01f *(1-this.empire.data.TaxRate));
            if (sspBudget < 0 || this.empire.data.SSPBudget > this.empire.Money * .1)
            {
                sspBudget = 0;

            }
            else
            {
                this.empire.Money -= sspBudget;
                this.empire.data.SSPBudget += sspBudget;
            }
            sspBudget = this.empire.data.SSPBudget *.1f;
            float roadMaintenance = 0;
            float nodeMaintenance = ResourceManager.ShipsDict["Subspace Projector"].GetMaintCost(this.empire);
            foreach (SpaceRoad roadBudget in this.empire.SpaceRoadsList)
            {
                if (roadBudget.NumberOfProjectors == 0)
                    roadBudget.NumberOfProjectors = roadBudget.RoadNodesList.Count;
                roadMaintenance += roadBudget.NumberOfProjectors * nodeMaintenance;
            }

            sspBudget -= roadMaintenance;

            //this.empire.data.SSPBudget += sspBudget;
            //sspBudget = this.empire.data.SSPBudget;
            float UnderConstruction = 0f;
            foreach (Goal g in this.Goals)
            {
                //if (g.GoalName == "BuildOffensiveShips")
                //    if (GlobalStats.ActiveModInfo != null && GlobalStats.ActiveModInfo.useProportionalUpkeep)
                //    {
                //        {
                //            UnderConstruction = UnderConstruction + ResourceManager.ShipsDict[g.ToBuildUID].GetMaintCostRealism();
                //        }
                //    }
                //    else
                //    {
                //        {
                //            UnderConstruction = UnderConstruction + ResourceManager.ShipsDict[g.ToBuildUID].GetMaintCost(this.empire);
                //        }
                //    }
                if (g.GoalName != "BuildConstructionShip")
                {
                    continue;
                }
                if (GlobalStats.ActiveModInfo != null && GlobalStats.ActiveModInfo.useProportionalUpkeep)
                {
                    UnderConstruction = UnderConstruction + ResourceManager.ShipsDict[g.ToBuildUID].GetMaintCostRealism();
                }
                else
                {
                    UnderConstruction = UnderConstruction + ResourceManager.ShipsDict[g.ToBuildUID].GetMaintCost(this.empire);
                }
            }
            sspBudget -= UnderConstruction;
            if (sspBudget > nodeMaintenance*2) //- nodeMaintenance * 5
            {
                foreach (SolarSystem ownedSystem in this.empire.GetOwnedSystems())
                //ReaderWriterLockSlim roadlock = new ReaderWriterLockSlim();
                //Parallel.ForEach(this.empire.GetOwnedSystems(), ownedSystem =>
                {

                    IOrderedEnumerable<SolarSystem> sortedList =
                        from otherSystem in this.empire.GetOwnedSystems()
                        orderby Vector2.Distance(otherSystem.Position, ownedSystem.Position)
                        select otherSystem;
                    int devLevelos = 0;
                    foreach (Planet p in ownedSystem.PlanetList)
                    {
                        if (p.Owner != this.empire)
                            continue;
                        //if (p.ps != Planet.GoodState.EXPORT && p.fs != Planet.GoodState.EXPORT)
                        //    continue;
                        devLevelos += p.developmentLevel;

                    }
                    if (devLevelos == 0)
                        //return;
                        continue;
                    foreach (SolarSystem Origin in sortedList)
                    {
                        if (Origin == ownedSystem)
                        {
                            continue;
                        }
                        int devLevel = devLevelos;
                        bool createRoad = true;
                        //roadlock.EnterReadLock();
                        foreach (SpaceRoad road in this.empire.SpaceRoadsList)
                        {
                            if (road.GetOrigin() != ownedSystem && road.GetDestination() != ownedSystem)
                            {
                                continue;
                            }
                            createRoad = false;
                        }
                       // roadlock.ExitReadLock();
                        foreach (Planet p in Origin.PlanetList)
                        {
                            if (p.Owner != this.empire)
                                continue;
                            devLevel += p.developmentLevel;
                        }
                        if (!createRoad)
                        {
                            continue;
                        }
                        SpaceRoad newRoad = new SpaceRoad(Origin, ownedSystem, this.empire, sspBudget, nodeMaintenance);

                        //roadlock.EnterWriteLock();
                        if (sspBudget <= 0 || newRoad.NumberOfProjectors == 0 || newRoad.NumberOfProjectors > devLevel)
                        {
                           // roadlock.ExitWriteLock();
                            continue;
                        }
                        sspBudget -= newRoad.NumberOfProjectors * nodeMaintenance;
                        UnderConstruction += newRoad.NumberOfProjectors * nodeMaintenance;

                            this.empire.SpaceRoadsList.Add(newRoad);
                           // roadlock.ExitWriteLock();
                    }
                }//);
            }
            sspBudget = this.empire.data.SSPBudget-roadMaintenance - UnderConstruction;
            List<SpaceRoad> ToRemove = new List<SpaceRoad>();
            //float income = this.empire.Money +this.empire.GrossTaxes; //this.empire.EstimateIncomeAtTaxRate(0.25f) +
            foreach (SpaceRoad road in this.empire.SpaceRoadsList.OrderBy(ssps => ssps.NumberOfProjectors))
            {

                if (road.RoadNodesList.Count == 0 ||sspBudget <= 0.0f )// || road.NumberOfProjectors ==0)
                {
                    //if(road.NumberOfProjectors ==0)
                    //{
                        //int rnc=0;
                        //foreach(RoadNode rn in road.RoadNodesList)
                        //{
                        //    foreach(Goal G in this.Goals)
                        //    {
                        //            if (G.type != GoalType.DeepSpaceConstruction || !(g.BuildPosition == rn.Position))
                        //            {
                        //                continue;
                        //            }

                        //    }
                        //    if (rn.Platform == null)
                        //        continue;
                        //    rnc++;
                        //}
                        //if (rnc > 0)
                        //    road.NumberOfProjectors = rnc;
                        //else
                     //       ToRemove.Add(road);

                    //else
                    ToRemove.Add(road);
                    sspBudget += road.NumberOfProjectors * nodeMaintenance;
                    continue;
                }

                RoadNode ssp = road.RoadNodesList.Where(notNull => notNull != null && notNull.Platform !=null).FirstOrDefault();
                if ((ssp != null && (!road.GetOrigin().OwnerList.Contains(this.empire) || !road.GetDestination().OwnerList.Contains(this.empire))))
                {
                    ToRemove.Add(road);
                    sspBudget += road.NumberOfProjectors * nodeMaintenance;
                    //if(ssp!=null )
                    //{
                    //    this.SSPBudget += road.NumberOfProjectors * nodeMaintenance;
                    //}
                }
                else
                {
                    foreach (RoadNode node in road.RoadNodesList)
                    {
                        if (node.Platform != null && (node.Platform == null || node.Platform.Active))
                        {
                            continue;
                        }
                        bool AddNew = true;
                        foreach (Goal g in this.Goals)
                        {
                            if (g.type != GoalType.DeepSpaceConstruction || !(g.BuildPosition == node.Position))
                            {
                                continue;
                            }
                            AddNew = false;
                        }
                        this.empire.BorderNodeLocker.EnterReadLock();
                        {
                            foreach (Empire.InfluenceNode bordernode in this.empire.BorderNodes)
                            {
                                if (Vector2.Distance(node.Position, bordernode.Position) >= bordernode.Radius)
                                {
                                    continue;
                                }
                                AddNew = false;
                            }
                        }
                        this.empire.BorderNodeLocker.ExitReadLock();
                        if (!AddNew)
                        {
                            continue;
                        }
                        Goal newRoad = new Goal(node.Position, "Subspace Projector", this.empire);
                        this.Goals.Add(newRoad);
                    }
                }
            }
            if (this.empire != Ship.universeScreen.player)
            {
                foreach (SpaceRoad road in ToRemove)
                {
                    this.empire.SpaceRoadsList.Remove(road);
                    foreach (RoadNode node in road.RoadNodesList)
                    {
                        if (node.Platform != null && node.Platform.Active ) //(node.Platform == null || node.Platform.Active))
                        {
                            node.Platform.Die(null,true); //.GetAI().OrderScrapShip();

                            continue;
                        }

                        foreach (Goal g in this.Goals)
                        {
                            if (g.type != GoalType.DeepSpaceConstruction || !(g.BuildPosition == node.Position))
                            {
                                continue;
                            }
                            this.Goals.QueuePendingRemoval(g);
                            foreach (Planet p in this.empire.GetPlanets())
                            {
                                foreach (QueueItem qi in p.ConstructionQueue)
                                {
                                    if (qi.Goal != g)
                                    {
                                        continue;
                                    }
                                    Planet productionHere = p;
                                    productionHere.ProductionHere = productionHere.ProductionHere + qi.productionTowards;
                                    if (p.ProductionHere > p.MAX_STORAGE)
                                    {
                                        p.ProductionHere = p.MAX_STORAGE;
                                    }
                                    p.ConstructionQueue.QueuePendingRemoval(qi);
                                }
                                p.ConstructionQueue.ApplyPendingRemovals();
                            }
                            this.empire.GetShips().thisLock.EnterReadLock();

                            foreach (Ship ship in this.empire.GetShips())
                            {
                                ship.GetAI().orderqueue.EnterReadLock();
                                bool flag = false;
                                ArtificialIntelligence.ShipGoal goal = ship.GetAI().OrderQueue.LastOrDefault();

                                if (goal == null || goal.goal == null || goal.goal.type != GoalType.DeepSpaceConstruction || goal.goal.BuildPosition != node.Position)
                                {
                                    flag = true;
                                }
                                ship.GetAI().orderqueue.ExitReadLock();
                                if (flag)
                                    continue;
                                ship.GetAI().OrderScrapShip();

                                break;

                            }
                            this.empire.GetShips().thisLock.ExitReadLock();

                        }
                        this.Goals.ApplyPendingRemovals();
                    }
                    this.empire.SpaceRoadsList.Remove(road);
                }
            }
        }
        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;
        }