//added by gremlin deveks drop bomb
        public void DropBomb(Bomb bomb)
        {
            if (bomb.owner == this.Owner)
            {
                return;
            }
            if (this.Owner != null && !this.Owner.GetRelations()[bomb.owner].AtWar && this.TurnsSinceTurnover > 10 && EmpireManager.GetEmpireByName(Planet.universeScreen.PlayerLoyalty) == bomb.owner)
            {
                this.Owner.GetGSAI().DeclareWarOn(bomb.owner, WarType.DefensiveWar);
            }
            this.CombatTimer = 10f;
            if (this.ShieldStrengthCurrent <= 0f)
            {
                float ran = RandomMath.RandomBetween(0f, 100f);
                bool hit = true;
                if (ran < 75f)
                {
                    hit = false;
                }
                Planet population = this;
                population.Population = population.Population - 1000f * ResourceManager.WeaponsDict[bomb.WeaponName].BombPopulationKillPerHit;
                AudioEmitter e = new AudioEmitter();
                e.Position = bomb.Position;
                if (Planet.universeScreen.viewState <= UniverseScreen.UnivScreenState.SystemView && this.system.isVisible)
                {
                    Cue Explode = AudioManager.GetCue("sd_bomb_impact_01");
                    Explode.Apply3D(Planet.universeScreen.listener, e);
                    Explode.Play();
                    ExplosionManager.AddExplosionNoFlames(bomb.Position, 200f, 7.5f, 0.6f);
                    Planet.universeScreen.flash.AddParticleThreadB(bomb.Position, Vector3.Zero);
                    for (int i = 0; i < 50; i++)
                    {
                        Planet.universeScreen.explosionParticles.AddParticleThreadB(bomb.Position, Vector3.Zero);
                    }
                }
                Planet.OrbitalDrop od = new Planet.OrbitalDrop();
                List<PlanetGridSquare> PotentialHits = new List<PlanetGridSquare>();
                if (hit)
                {
                    int buildingcount = 0;
                    foreach (PlanetGridSquare pgs in this.TilesList)
                    {
                        if (pgs.building == null && pgs.TroopsHere.Count <= 0)
                        {
                            continue;
                        }
                        PotentialHits.Add(pgs);
                        if(pgs.building!=null)
                        {
                            buildingcount++;
                        }
                    }
                    if ( PotentialHits.Count <= 0)
                    {
                        hit = false;
                        if (this.BuildingList.Count > 0)
                            this.BuildingList.Clear();
                    }
                    else
                    {
                        int ranhit = (int)RandomMath.RandomBetween(0f, (float)PotentialHits.Count + 1f);
                        if (ranhit > PotentialHits.Count - 1)
                        {
                            ranhit = PotentialHits.Count - 1;
                        }
                        od.Target = PotentialHits[ranhit];
                    }
                }
                if (!hit)
                {
                    int row = (int)RandomMath.RandomBetween(0f, 5f);
                    int column = (int)RandomMath.RandomBetween(0f, 7f);
                    if (row > 4)
                    {
                        row = 4;
                    }
                    if (column > 6)
                    {
                        column = 6;
                    }
                    foreach (PlanetGridSquare pgs in this.TilesList)
                    {
                        if (pgs.x != column || pgs.y != row)
                        {
                            continue;
                        }
                        od.Target = pgs;
                        break;
                    }
                }
                if (od.Target.TroopsHere.Count > 0)
                {
                    Troop item = od.Target.TroopsHere[0];
                    item.Strength = item.Strength - (int)RandomMath.RandomBetween((float)ResourceManager.WeaponsDict[bomb.WeaponName].BombTroopDamage_Min, (float)ResourceManager.WeaponsDict[bomb.WeaponName].BombTroopDamage_Max);
                    if (od.Target.TroopsHere[0].Strength <= 0)
                    {
                        this.TroopsHere.Remove(od.Target.TroopsHere[0]);
                        od.Target.TroopsHere.Clear();
                    }
                }
                else if (od.Target.building != null)
                {
                    Building target = od.Target.building;
                    target.Strength = target.Strength - (int)RandomMath.RandomBetween((float)ResourceManager.WeaponsDict[bomb.WeaponName].BombHardDamageMin, (float)ResourceManager.WeaponsDict[bomb.WeaponName].BombHardDamageMax);
                    if (od.Target.building.CombatStrength > 0)
                    {
                        od.Target.building.CombatStrength = od.Target.building.Strength;
                    }
                    if (od.Target.building.Strength <= 0)
                    {
                        this.BuildingList.Remove(od.Target.building);
                        od.Target.building = null;

                        bool flag = od.Target.Biosphere;
                        //Added Code here
                        od.Target.Habitable = false;
                        od.Target.highlighted = false;
                        od.Target.Biosphere = false;
                        this.TerraformPoints--;
                        //Building Wasteland = new Building;
                        //Wasteland.Name="Fissionables";
                        //od.Target.building=Wasteland;
                        if (flag)
                        {
                            foreach (Building bios in this.BuildingList)
                            {
                                if (bios.Name == "Biospheres")
                                {
                                    od.Target.building = bios;
                                    break;
                                }
                            }
                            if (od.Target.building != null)
                            {
                                this.Population -= od.Target.building.MaxPopIncrease;
                                this.BuildingList.Remove(od.Target.building);
                                od.Target.building = null;
                            }
                        }

                    }
                }
                if (Planet.universeScreen.workersPanel is CombatScreen && Planet.universeScreen.LookingAtPlanet && (Planet.universeScreen.workersPanel as CombatScreen).p == this)
                {
                    AudioManager.PlayCue("Explo1");
                    CombatScreen.SmallExplosion exp1 = new CombatScreen.SmallExplosion(4);
                    exp1.grid = od.Target.ClickRect;
                    lock (GlobalStats.ExplosionLocker)
                    {
                        (Planet.universeScreen.workersPanel as CombatScreen).Explosions.Add(exp1);
                    }
                }
                if (this.Population <= 0f)
                {
                    this.Population = 0f;
                    if (this.Owner != null)
                    {
                        this.Owner.GetPlanets().Remove(this);
                        if (this.ExploredDict[EmpireManager.GetEmpireByName(Planet.universeScreen.PlayerLoyalty)])
                        {
                            Planet.universeScreen.NotificationManager.AddPlanetDiedNotification(this, EmpireManager.GetEmpireByName(Planet.universeScreen.PlayerLoyalty));
                        }
                        bool removeowner = true;
                        if (this.Owner != null)
                        {
                            foreach (Planet other in this.system.PlanetList)
                            {
                                if (other.Owner != this.Owner || other == this)
                                {
                                    continue;
                                }
                                removeowner = false;
                            }
                            if (removeowner)
                            {
                                this.system.OwnerList.Remove(this.Owner);
                            }
                        }
                        this.ConstructionQueue.Clear();
                        this.Owner = null;
                        return;
                    }
                }
                if (ResourceManager.WeaponsDict[bomb.WeaponName].HardCodedAction != null)
                {
                    string hardCodedAction = ResourceManager.WeaponsDict[bomb.WeaponName].HardCodedAction;
                    string str = hardCodedAction;
                    if (hardCodedAction != null)
                    {
                        if (str != "Free Owlwoks")
                        {
                            return;
                        }
                        if (this.Owner != null && this.Owner == EmpireManager.GetEmpireByName("Cordrazine Collective"))
                        {
                            for (int i = 0; i < this.TroopsHere.Count; i++)
                            {
                                if (this.TroopsHere[i].GetOwner() == EmpireManager.GetEmpireByName("Cordrazine Collective") && this.TroopsHere[i].TargetType == "Soft")
                                {
                                    if (SteamManager.SetAchievement("Owlwoks_Freed"))
                                    {
                                        SteamManager.SaveAllStatAndAchievementChanges();
                                    }
                                    this.TroopsHere[i].SetOwner(bomb.owner);
                                    this.TroopsHere[i].Name = Localizer.Token(EmpireManager.GetEmpireByName("Cordrazine Collective").data.TroopNameIndex);
                                    this.TroopsHere[i].Description = Localizer.Token(EmpireManager.GetEmpireByName("Cordrazine Collective").data.TroopDescriptionIndex);
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                AudioEmitter emitter = new AudioEmitter();
                emitter.Position = this.shield.Center;
                if (Planet.universeScreen.viewState <= UniverseScreen.UnivScreenState.SystemView)
                {
                    Cue shieldcue = AudioManager.GetCue("sd_impact_shield_01");
                    shieldcue.Apply3D(Planet.universeScreen.listener, emitter);
                    shieldcue.Play();
                }
                this.shield.Rotation = MathHelper.ToRadians(HelperFunctions.findAngleToTarget(this.Position, new Vector2(bomb.Position.X, bomb.Position.Y)));
                this.shield.displacement = 0f;
                this.shield.texscale = 2.8f;
                this.shield.Radius = this.SO.WorldBoundingSphere.Radius + 100f;
                this.shield.displacement = 0.085f * RandomMath.RandomBetween(1f, 10f);
                this.shield.texscale = 2.8f;
                this.shield.texscale = 2.8f - 0.185f * RandomMath.RandomBetween(1f, 10f);
                this.shield.Center = new Vector3(this.Position.X, this.Position.Y, 2500f);
                this.shield.pointLight.World = bomb.GetWorld();
                this.shield.pointLight.DiffuseColor = new Vector3(0.5f, 0.5f, 1f);
                this.shield.pointLight.Radius = 50f;
                this.shield.pointLight.Intensity = 8f;
                this.shield.pointLight.Enabled = true;
                Vector3 vel = Vector3.Normalize(bomb.Position - this.shield.Center);
                if (Planet.universeScreen.viewState <= UniverseScreen.UnivScreenState.SystemView)
                {
                    Planet.universeScreen.flash.AddParticleThreadB(bomb.Position, Vector3.Zero);
                    for (int i = 0; i < 200; i++)
                    {
                        Planet.universeScreen.sparks.AddParticleThreadB(bomb.Position, vel * new Vector3(RandomMath.RandomBetween(-25f, 25f), RandomMath.RandomBetween(-25f, 25f), RandomMath.RandomBetween(-25f, 25f)));
                    }
                }
                Planet shieldStrengthCurrent = this;
                shieldStrengthCurrent.ShieldStrengthCurrent = shieldStrengthCurrent.ShieldStrengthCurrent - (float)ResourceManager.WeaponsDict[bomb.WeaponName].BombTroopDamage_Max;
                if (this.ShieldStrengthCurrent < 0f)
                {
                    this.ShieldStrengthCurrent = 0f;
                    return;
                }
            }
        }
 public void DropBombORIG(Bomb bomb)
 {
     if (bomb.owner == this.Owner)
         return;
     if (this.Owner != null && !this.Owner.GetRelations()[bomb.owner].AtWar && (this.TurnsSinceTurnover > 10 && EmpireManager.GetEmpireByName(Planet.universeScreen.PlayerLoyalty) == bomb.owner))
         this.Owner.GetGSAI().DeclareWarOn(bomb.owner, WarType.DefensiveWar);
     if ((double)this.ShieldStrengthCurrent > 0.0)
     {
         AudioEmitter emitter = new AudioEmitter();
         emitter.Position = this.shield.Center;
         if (Planet.universeScreen.viewState <= UniverseScreen.UnivScreenState.SystemView)
         {
             Cue cue = AudioManager.GetCue("sd_impact_shield_01");
             cue.Apply3D(Planet.universeScreen.listener, emitter);
             cue.Play();
         }
         this.shield.Rotation = MathHelper.ToRadians(HelperFunctions.findAngleToTarget(this.Position, new Vector2(bomb.Position.X, bomb.Position.Y)));
         this.shield.displacement = 0.0f;
         this.shield.texscale = 2.8f;
         this.shield.Radius = this.SO.WorldBoundingSphere.Radius + 100f;
         this.shield.displacement = 0.085f * RandomMath.RandomBetween(1f, 10f);
         this.shield.texscale = 2.8f;
         this.shield.texscale = (float)(2.79999995231628 - 0.185000002384186 * (double)RandomMath.RandomBetween(1f, 10f));
         this.shield.Center = new Vector3(this.Position.X, this.Position.Y, 2500f);
         this.shield.pointLight.World = bomb.GetWorld();
         this.shield.pointLight.DiffuseColor = new Vector3(0.5f, 0.5f, 1f);
         this.shield.pointLight.Radius = 50f;
         this.shield.pointLight.Intensity = 8f;
         this.shield.pointLight.Enabled = true;
         Vector3 vector3 = Vector3.Normalize(bomb.Position - this.shield.Center);
         if (Planet.universeScreen.viewState <= UniverseScreen.UnivScreenState.SystemView)
         {
             Planet.universeScreen.flash.AddParticleThreadB(bomb.Position, Vector3.Zero);
             for (int index = 0; index < 200; ++index)
                 Planet.universeScreen.sparks.AddParticleThreadB(bomb.Position, vector3 * new Vector3(RandomMath.RandomBetween(-25f, 25f), RandomMath.RandomBetween(-25f, 25f), RandomMath.RandomBetween(-25f, 25f)));
         }
         this.ShieldStrengthCurrent -= (float)ResourceManager.WeaponsDict[bomb.WeaponName].BombTroopDamage_Max;
         if ((double)this.ShieldStrengthCurrent >= 0.0)
             return;
         this.ShieldStrengthCurrent = 0.0f;
     }
     else
     {
         float num1 = RandomMath.RandomBetween(0.0f, 100f);
         bool flag1 = true;
         if ((double)num1 < 75.0)
             flag1 = false;
         this.Population -= 1000f * ResourceManager.WeaponsDict[bomb.WeaponName].BombPopulationKillPerHit;
         AudioEmitter emitter = new AudioEmitter();
         emitter.Position = bomb.Position;
         if (Planet.universeScreen.viewState <= UniverseScreen.UnivScreenState.SystemView && this.system.isVisible)
         {
             Cue cue = AudioManager.GetCue("sd_bomb_impact_01");
             cue.Apply3D(Planet.universeScreen.listener, emitter);
             cue.Play();
             ExplosionManager.AddExplosionNoFlames(bomb.Position, 200f, 7.5f, 0.6f);
             Planet.universeScreen.flash.AddParticleThreadB(bomb.Position, Vector3.Zero);
             for (int index = 0; index < 50; ++index)
                 Planet.universeScreen.explosionParticles.AddParticleThreadB(bomb.Position, Vector3.Zero);
         }
         Planet.OrbitalDrop orbitalDrop = new Planet.OrbitalDrop();
         List<PlanetGridSquare> list = new List<PlanetGridSquare>();
         if (flag1)
         {
             foreach (PlanetGridSquare planetGridSquare in this.TilesList)
             {
                 if (planetGridSquare.building != null || planetGridSquare.TroopsHere.Count > 0)
                     list.Add(planetGridSquare);
             }
             if (list.Count > 0)
             {
                 int index = (int)RandomMath.RandomBetween(0.0f, (float)list.Count + 1f);
                 if (index > list.Count - 1)
                     index = list.Count - 1;
                 orbitalDrop.Target = list[index];
             }
             else
                 flag1 = false;
         }
         if (!flag1)
         {
             int num2 = (int)RandomMath.RandomBetween(0.0f, 5f);
             int num3 = (int)RandomMath.RandomBetween(0.0f, 7f);
             if (num2 > 4)
                 num2 = 4;
             if (num3 > 6)
                 num3 = 6;
             foreach (PlanetGridSquare planetGridSquare in this.TilesList)
             {
                 if (planetGridSquare.x == num3 && planetGridSquare.y == num2)
                 {
                     orbitalDrop.Target = planetGridSquare;
                     break;
                 }
             }
         }
         if (orbitalDrop.Target.TroopsHere.Count > 0)
         {
             orbitalDrop.Target.TroopsHere[0].Strength -= (int)RandomMath.RandomBetween((float)ResourceManager.WeaponsDict[bomb.WeaponName].BombTroopDamage_Min, (float)ResourceManager.WeaponsDict[bomb.WeaponName].BombTroopDamage_Max);
             if (orbitalDrop.Target.TroopsHere[0].Strength <= 0)
             {
                 this.TroopsHere.Remove(orbitalDrop.Target.TroopsHere[0]);
                 orbitalDrop.Target.TroopsHere.Clear();
             }
         }
         else if (orbitalDrop.Target.building != null)
         {
             orbitalDrop.Target.building.Strength -= (int)RandomMath.RandomBetween((float)ResourceManager.WeaponsDict[bomb.WeaponName].BombHardDamageMin, (float)ResourceManager.WeaponsDict[bomb.WeaponName].BombHardDamageMax);
             if (orbitalDrop.Target.building.CombatStrength > 0)
                 orbitalDrop.Target.building.CombatStrength = orbitalDrop.Target.building.Strength;
             if (orbitalDrop.Target.building.Strength <= 0)
             {
                 this.BuildingList.Remove(orbitalDrop.Target.building);
                 orbitalDrop.Target.building = (Building)null;
             }
         }
         if (Planet.universeScreen.workersPanel is CombatScreen && Planet.universeScreen.LookingAtPlanet && (Planet.universeScreen.workersPanel as CombatScreen).p == this)
         {
             AudioManager.PlayCue("Explo1");
             CombatScreen.SmallExplosion smallExplosion = new CombatScreen.SmallExplosion(4);
             smallExplosion.grid = orbitalDrop.Target.ClickRect;
             lock (GlobalStats.ExplosionLocker)
                 (Planet.universeScreen.workersPanel as CombatScreen).Explosions.Add(smallExplosion);
         }
         if ((double)this.Population <= 0.0)
         {
             this.Population = 0.0f;
             if (this.Owner != null)
             {
                 this.Owner.GetPlanets().Remove(this);
                 if (this.ExploredDict[EmpireManager.GetEmpireByName(Planet.universeScreen.PlayerLoyalty)])
                 {
                     Planet.universeScreen.NotificationManager.AddPlanetDiedNotification(this, EmpireManager.GetEmpireByName(Planet.universeScreen.PlayerLoyalty));
                     bool flag2 = true;
                     if (this.Owner != null)
                     {
                         foreach (Planet planet in this.system.PlanetList)
                         {
                             if (planet.Owner == this.Owner && planet != this)
                                 flag2 = false;
                         }
                         if (flag2)
                             this.system.OwnerList.Remove(this.Owner);
                     }
                     this.ConstructionQueue.Clear();
                     this.Owner = (Empire)null;
                     return;
                 }
             }
         }
         if (ResourceManager.WeaponsDict[bomb.WeaponName].HardCodedAction == null)
             return;
         switch (ResourceManager.WeaponsDict[bomb.WeaponName].HardCodedAction)
         {
             case "Free Owlwoks":
                 if (this.Owner == null || this.Owner != EmpireManager.GetEmpireByName("Cordrazine Collective"))
                     break;
                 for (int index = 0; index < this.TroopsHere.Count; ++index)
                 {
                     if (this.TroopsHere[index].GetOwner() == EmpireManager.GetEmpireByName("Cordrazine Collective") && this.TroopsHere[index].TargetType == "Soft")
                     {
     #if STEAM
                         if (SteamManager.SetAchievement("Owlwoks_Freed"))
                             SteamManager.SaveAllStatAndAchievementChanges();
     #endif
                         this.TroopsHere[index].SetOwner(bomb.owner);
                         this.TroopsHere[index].Name = Localizer.Token(EmpireManager.GetEmpireByName("Cordrazine Collective").data.TroopNameIndex);
                         this.TroopsHere[index].Description = Localizer.Token(EmpireManager.GetEmpireByName("Cordrazine Collective").data.TroopDescriptionIndex);
                     }
                 }
                 break;
         }
     }
 }
        //added by gremlin Devekmod AuUpdate(fixed)
        public void Update(float elapsedTime)
        {
            this.CombatAI.UpdateCombatAI(this.Owner);
            ArtificialIntelligence.ShipGoal toEvaluate;
            if (this.State == AIState.AwaitingOrders && this.DefaultAIState == AIState.Exterminate)
            {
                this.State = AIState.Exterminate;
            }
            if (this.Owner.Name == "Subspace Projector")
            {
                this.BadGuysNear = true;
                return;
            }
            if (this.ClearOrdersNext)
            {
                this.OrderQueue.Clear();
                this.ClearOrdersNext = false;
                this.State = AIState.AwaitingOrders;
            }
            List<Ship> ToRemove = new List<Ship>();
            foreach (Ship target in this.TargetQueue)
            {
                if (target.Active)
                {
                    continue;
                }
                ToRemove.Add(target);
            }
            foreach (Ship ship in ToRemove)
            {
                this.TargetQueue.Remove(ship);
            }
            if (!this.hasPriorityTarget)
            {
                this.TargetQueue.Clear();
            }
            if (this.Owner.loyalty == ArtificialIntelligence.universeScreen.player && (  this.State == AIState.MoveTo && Vector2.Distance(this.Owner.Center, this.MovePosition) > 100f || this.State == AIState.Orbit || (this.State == AIState.Bombard || this.State == AIState.AssaultPlanet || this.State == AIState.BombardTroops) || this.State == AIState.Rebase || this.State == AIState.Scrap || this.State == AIState.Resupply || this.State == AIState.Refit || this.State == AIState.FormationWarp))
            {
                this.HasPriorityOrder = true;
            }
            if (this.State == AIState.Resupply)
            {
                this.HasPriorityOrder = true;
                if (this.Owner.Ordinance >= this.Owner.OrdinanceMax)
                {
                    this.HasPriorityOrder = false;
                }
            }
            //if (this.State == AIState.Flee && !this.BadGuysNear)// Vector2.Distance(this.OrbitTarget.Position, this.Owner.Position) < this.Owner.SensorRange + 10000)
            //{
            //    if(this.OrderQueue.Count > 0)
            //        this.OrderQueue.Remove(this.OrderQueue.Last);
            //    if (this.Owner.CargoSpace_Used > 0)
            //        this.State = AIState.SystemTrader;
            //    else
            //        this.State = this.DefaultAIState;
            //}
            this.ScanForThreatTimer -=  elapsedTime;
            if (this.ScanForThreatTimer < 0f)
            {
                if (this.inOrbit == true )//&& !(this.State == AIState.Orbit ||                     this.State == AIState.Flee))
                {
                    this.inOrbit = false;
                }
                this.SetCombatStatus(elapsedTime);
                this.ScanForThreatTimer = 2f;
                if (this.Owner.loyalty.data.Traits.Pack)
                {
                    this.Owner.DamageModifier = -0.25f;
                    Ship owner = this.Owner;
                    owner.DamageModifier = owner.DamageModifier + 0.05f * (float)this.FriendliesNearby.Count;
                    if (this.Owner.DamageModifier > 0.5f)
                    {
                        this.Owner.DamageModifier = 0.5f;
                    }
                }
            }
            this.UtilityModuleCheckTimer -= elapsedTime;
            if (this.UtilityModuleCheckTimer <= 0f)
            {
                this.UtilityModuleCheckTimer = 1f;
                //Added by McShooterz: logic for transporter moduels
                if (this.Owner.hasTransporter)
                {
                    foreach (ShipModule module in this.Owner.Transporters)
                    {
                        if (module.TransporterTimer <= 0f && module.Active && module.Powered && module.TransporterPower < this.Owner.PowerCurrent)
                        {
                            if (this.FriendliesNearby.Count > 0 && module.TransporterOrdnance > 0 && this.Owner.Ordinance > 0)
                                this.DoOrdinanceTransporterLogic(module);
                            if (module.TransporterTroopAssault > 0 && this.Owner.TroopList.Count() > 0)
                                this.DoAssaultTransporterLogic(module);
                        }
                    }
                }
                //Do repair check if friendly ships around and no combat
                if (!this.Owner.InCombat && this.FriendliesNearby.Count > 0)
                {
                    //Added by McShooterz: logic for repair beams
                    if (this.Owner.hasRepairBeam)
                    {
                        foreach (ShipModule module in this.Owner.RepairBeams)
                        {
                            if (module.InstalledWeapon.timeToNextFire <= 0f && module.InstalledWeapon.moduleAttachedTo.Powered && this.Owner.Ordinance >= module.InstalledWeapon.OrdinanceRequiredToFire && this.Owner.PowerCurrent >= module.InstalledWeapon.PowerRequiredToFire)
                            {
                                this.DoRepairBeamLogic(module.InstalledWeapon);
                            }
                        }
                    }
                    if (this.Owner.HasRepairModule)
                    {
                        foreach (Weapon weapon in this.Owner.Weapons)
                        {
                            if (weapon.timeToNextFire > 0f || !weapon.moduleAttachedTo.Powered || this.Owner.Ordinance < weapon.OrdinanceRequiredToFire || this.Owner.PowerCurrent < weapon.PowerRequiredToFire || !weapon.IsRepairDrone)
                            {
                                continue;
                            }
                            this.DoRepairDroneLogic(weapon);
                        }
                    }
                }
            }
            if (this.State == AIState.ManualControl)
            {
                return;
            }
            this.ReadyToWarp = true;
            this.Owner.isThrusting = false;
            this.Owner.isTurning = false;

            #region old flee code
            //if (!this.HasPriorityOrder
            //    && (this.BadGuysNear || this.Owner.InCombat)
            //    && (this.Owner.shipData == null || this.Owner.shipData.ShipCategory == ShipData.Category.Civilian)
            //    && this.Owner.Weapons.Count == 0 && this.Owner.GetHangars().Count == 0 && this.Owner.Transporters.Count() == 0
            //    && (this.Owner.Role !="troop"
            //    && this.Owner.Role != "construction"
            //    && this.State !=AIState.Colonize
            //    && !this.IgnoreCombat && this.State != AIState.Rebase)
            //    && (this.Owner.Role == "freighter" || this.Owner.fleet == null || this.Owner.Mothership != null))
            //{
            //    if (this.State != AIState.Flee )
            //    {
            //        this.HasPriorityOrder = true;
            //        this.State = AIState.Flee;
            //        if (this.State == AIState.Flee)
            //        {
            //            this.OrderFlee(false);
            //            this.Owner.InCombatTimer = 15f;

            //        }
            //    }
            //    else if (this.State == AIState.Flee && (this.OrbitTarget != null && Vector2.Distance(this.OrbitTarget.Position, this.Owner.Position) < this.Owner.SensorRange + 10000))
            //    {
            //        this.State = this.DefaultAIState;
            //    }
            //}
            #endregion
            if (this.State == AIState.SystemTrader && this.start != null && this.end != null && (this.start.Owner != this.Owner.loyalty || this.end.Owner != this.Owner.loyalty))
            {
                this.start = null;
                this.end = null;
                this.OrderTrade();
                return;
            }
            if (this.State == AIState.PassengerTransport && this.start != null && this.end != null && (this.start.Owner != this.Owner.loyalty || this.end.Owner != this.Owner.loyalty))
            {
                this.start = null;
                this.end = null;
                this.OrderTransportPassengers();
                return;
            }
            #if !DEBUG
            try
            {
            #endif
                if (this.OrderQueue.Count == 0)
                {
                    if (this.Owner.fleet == null)
                    {
                        lock (this.wayPointLocker)
                        {
                            this.ActiveWayPoints.Clear();
                        }
                        AIState state = this.State;
                        if (state <= AIState.MoveTo)
                        {
                            if (state <= AIState.SystemTrader)
                            {
                                if (state == AIState.DoNothing)
                                {
                                    this.AwaitOrders(elapsedTime);
                                }
                                else
                                {
                                    switch (state)
                                    {
                                        case AIState.AwaitingOrders:
                                            {
                                                if (this.Owner.loyalty != ArtificialIntelligence.universeScreen.player)
                                                {
                                                    this.AwaitOrders(elapsedTime);
                                                }
                                                else
                                                {
                                                    this.AwaitOrdersPlayer(elapsedTime);
                                                }
                                                if (this.Owner.OrdinanceMax == 0 || this.Owner.OrdinanceMax > 0 && this.Owner.Ordinance / this.Owner.OrdinanceMax >= 0.2f)
                                                {

                                                    break;

                                                }
                                                if (FriendliesNearby.Where(supply => supply.HasSupplyBays && supply.Ordinance >= 100).Count() > 0)
                                                {
                                                    break;
                                                }
                                                List<Planet> shipyards = new List<Planet>();
                                                for (int i = 0; i < this.Owner.loyalty.GetPlanets().Count; i++)
                                                {
                                                    Planet item = this.Owner.loyalty.GetPlanets()[i];
                                                    if (item.HasShipyard)
                                                    {
                                                        shipyards.Add(item);
                                                    }
                                                }
                                                IOrderedEnumerable<Planet> sortedList =
                                                    from p in shipyards
                                                    orderby Vector2.Distance(this.Owner.Center, p.Position)
                                                    select p;
                                                if (sortedList.Count<Planet>() <= 0)
                                                {
                                                    break;
                                                }
                                                this.OrderResupply(sortedList.First<Planet>(), true);
                                                break;
                                            }
                                        case AIState.Escort:
                                            {
                                                if (this.EscortTarget != this.Owner.Mothership || this.Owner.Mothership == null || !this.Owner.Mothership.InCombat)
                                                {
                                                    if (this.EscortTarget == null || !this.EscortTarget.Active)
                                                    {
                                                        this.State = AIState.AwaitingOrders;   //fbedard
                                                        break;
                                                    }
                                                    this.OrbitShip(this.EscortTarget, elapsedTime);
                                                    break;
                                                }
                                                else
                                                {
                                                    if(this.Target == null && !(this.hasPriorityTarget || this.HasPriorityOrder))
                                                    this.Target = this.Owner.Mothership.GetAI().Target;
                                                    this.DoCombat(elapsedTime);
                                                    break;
                                                }
                                            }
                                        case AIState.SystemTrader:
                                            {
                                                this.OrderTrade();
                                                if (this.end != null && this.start != null)
                                                {
                                                    break;
                                                }
                                                this.AwaitOrders(elapsedTime);
                                                break;
                                            }
                                    }
                                }
                            }
                            else if (state == AIState.PassengerTransport)
                            {
                                this.OrderTransportPassengers();
                                if (this.end == null || this.start == null)
                                {
                                    this.AwaitOrders(elapsedTime);
                                }
                            }
                            else if (state != AIState.MoveTo)
                            {
                            }
                        }
                        else if (state <= AIState.ReturnToHangar)
                        {
                            switch (state)
                            {
                                case AIState.SystemDefender:
                                    {
                                        if (this.Target != null)
                                        System.Diagnostics.Debug.WriteLine("SD Tatget" + this.Owner.VanityName);
                                        //if(this.Target == null)
                                        this.AwaitOrders(elapsedTime);
                                        break;
                                    }
                                case AIState.AwaitingOffenseOrders:
                                    {
                                        break;
                                    }
                                case AIState.Resupply:
                                    {
                                        if (this.Owner.Ordinance != this.Owner.OrdinanceMax)
                                        {
                                            break;
                                        }
                                        this.State = AIState.AwaitingOrders;
                                        break;
                                    }
                                default:
                                    {
                                        if (state == AIState.ReturnToHangar)
                                        {
                                            this.DoReturnToHangar(elapsedTime);
                                            break;
                                        }
                                        else
                                        {
                                            break;
                                        }
                                    }
                            }
                        }
                        else if (state != AIState.Intercept)
                        {
                            if (state == AIState.Exterminate)
                            {
                                this.OrderFindExterminationTarget(true);
                            }
                        }
                        else if (this.Target != null)
                        {
                            this.OrbitShip(this.Target as Ship, elapsedTime);
                        }
                    }
                    else
                    {
                        float DistanceToFleetOffset = Vector2.Distance(this.Owner.Center, this.Owner.fleet.Position + this.Owner.FleetOffset);
                        Vector2 toAdd = (this.Owner.Velocity != Vector2.Zero ? Vector2.Normalize(this.Owner.Velocity) : Vector2.Zero) * 100f;
                        Vector2.Distance(this.Owner.Center, (this.Owner.fleet.Position + this.Owner.FleetOffset) + toAdd);
                        Vector2 vector2 = HelperFunctions.findPointFromAngleAndDistanceUsingRadians(this.Owner.fleet.Position + this.Owner.FleetOffset, this.Owner.fleet.facing, 1f);
                        Vector2 fvec = HelperFunctions.FindVectorToTarget(Vector2.Zero, vector2);
                        if (DistanceToFleetOffset <= 75f || this.HasPriorityOrder)
                        {
                            this.Owner.Velocity = Vector2.Zero;
                            vector2 = HelperFunctions.findPointFromAngleAndDistanceUsingRadians(Vector2.Zero, this.Owner.fleet.facing, 1f);
                            fvec = HelperFunctions.FindVectorToTarget(Vector2.Zero, vector2);
                            Vector2 wantedForward = Vector2.Normalize(fvec);
                            Vector2 forward = new Vector2((float)Math.Sin((double)this.Owner.Rotation), -(float)Math.Cos((double)this.Owner.Rotation));
                            Vector2 right = new Vector2(-forward.Y, forward.X);
                            float angleDiff = (float)Math.Acos((double)Vector2.Dot(wantedForward, forward));
                            float facing = (Vector2.Dot(wantedForward, right) > 0f ? 1f : -1f);
                            if (angleDiff > 0.02f)
                            {
                                this.RotateToFacing(elapsedTime, angleDiff, facing);
                            }
                            this.State = AIState.AwaitingOrders;
                        }
                        else
                        {
                            this.ThrustTowardsPosition(this.Owner.fleet.Position + this.Owner.FleetOffset, elapsedTime, this.Owner.fleet.speed);
                            lock (this.wayPointLocker)
                            {
                                this.ActiveWayPoints.Clear();
                                this.ActiveWayPoints.Enqueue(this.Owner.fleet.Position + this.Owner.FleetOffset);
                                if (this.Owner.fleet.GetStack().Count > 0)
                                {
                                    this.ActiveWayPoints.Enqueue(this.Owner.fleet.GetStack().Peek().MovePosition + this.Owner.FleetOffset);
                                }
                            }
                        }
                    }
                }
                else if (this.OrderQueue.Count > 0)
                {
            #if DEBUG
                    try
            #endif
                    {
                        toEvaluate = this.OrderQueue.First<ArtificialIntelligence.ShipGoal>();
                    }
            #if DEBUG
                    catch

                    {
                        return;
                    }
            #endif
                    Planet target = toEvaluate.TargetPlanet;
                    switch (toEvaluate.Plan)
                    {
                        case ArtificialIntelligence.Plan.HoldPosition:
                            {
                                //

                                //
                                this.HoldPosition();

                                break;
                            }
                        case ArtificialIntelligence.Plan.Stop:
                            {
                                this.Stop(elapsedTime, toEvaluate);
                                break;
                            }
                        case ArtificialIntelligence.Plan.Scrap:
                            {
                                this.ScrapShip(elapsedTime, toEvaluate);
                                break;
                            }
                        case ArtificialIntelligence.Plan.Bombard:
                            //target = toEvaluate.TargetPlanet; //Modified by Ermenildo V. Castro, Jr.; 07/29/15: Removed redunant statement, assignment occurs before SWITCH
                            if (this.Owner.Ordinance < 0.05* this.Owner.OrdinanceMax
                                || (target.TroopsHere.Count <= target.TroopsHere.Count * .40f  || target.Population <= target.Population * .10f) //Legacy Code: (target.BuildingList.Count == 0 && target.TroopsHere.Count == 0  && target.Population <0f)
                                                                                                                              //Modified by Ermenildo V. Castro, Jr. for Issue #488
                                                                                                                              //Issue #488:
                                                                                                                              //The ai needs to soften planets more for invasion but try not to kill all the populace
                                                                                                                              //Modified conditional to reflect goals for Issue #488:
                                                                                                                              //        - Stop bombarding if planet population is less than 10% of the original target population
                                                                                                                              //        - Stop bombarding if opposition troops are attrited by at least 60%, id est: target troops less than 40% of original troop count
                                || target.GetGroundStrengthOther(this.Owner.loyalty) * 1.5
                                <= target.GetGroundStrength(this.Owner.loyalty)
                                )
                            {
                                this.OrderQueue.Clear();
                                if(this.CombatState == CombatState.Evade)
                                this.State = AIState.AwaitingOrders;
                                this.HasPriorityOrder = false;
                            }
                            this.DoOrbit(toEvaluate.TargetPlanet, elapsedTime);
                            float radius = toEvaluate.TargetPlanet.ObjectRadius + this.Owner.Radius + 1000;
                            if (toEvaluate.TargetPlanet.Owner == this.Owner.loyalty) //cannot bombard friednly planets
                            {
                                this.OrderQueue.Clear();
                                return;
                            }
                            else if (Vector2.Distance(this.Owner.Center, toEvaluate.TargetPlanet.Position) < radius)
                            {
                                using (List<ShipModule>.Enumerator enumerator = this.Owner.BombBays.GetEnumerator())
                                {
                                    while (enumerator.MoveNext())
                                    {
                                        ShipModule current = enumerator.Current;
                                        if ((double)current.BombTimer <= 0.0)
                                        {
                                            Bomb bomb = new Bomb(new Vector3(this.Owner.Center, 0.0f), this.Owner.loyalty);
                                            bomb.WeaponName = current.BombType;
                                            if ((double)this.Owner.Ordinance > (double)ResourceManager.WeaponsDict[current.BombType].OrdinanceRequiredToFire)
                                            {
                                                this.Owner.Ordinance -= ResourceManager.WeaponsDict[current.BombType].OrdinanceRequiredToFire;
                                                bomb.SetTarget(toEvaluate.TargetPlanet);
                                                //lock (GlobalStats.BombLock)
                                                    ArtificialIntelligence.universeScreen.BombList.Add(bomb);
                                                current.BombTimer = ResourceManager.WeaponsDict[current.BombType].fireDelay;
                                            }
                                        }
                                    }
                                    break;
                                }
                            }
                            else
                                break;
                        case ArtificialIntelligence.Plan.BombTroops:
                            target = toEvaluate.TargetPlanet;

                            if (target.TroopsHere.Where(unfriendlyTroops => unfriendlyTroops.GetOwner() != this.Owner.loyalty).Count() * 1.5
                                >= target.TilesList.Sum(space => space.number_allowed_troops))
                            {
                                if ((double)this.Owner.Ordinance < 0.0500000007450581 * (double)this.Owner.OrdinanceMax)
                                {
                                    this.OrderQueue.Clear();
                                    this.State = AIState.AwaitingOrders;
                                    this.HasPriorityOrder = false;
                                }
                                this.DoOrbit(toEvaluate.TargetPlanet, elapsedTime);
                                 radius = toEvaluate.TargetPlanet.ObjectRadius + this.Owner.Radius + 1000;
                                if (toEvaluate.TargetPlanet.Owner == this.Owner.loyalty)

                                {
                                    this.OrderQueue.Clear();
                                    return;
                                }
                                else if ((double)Vector2.Distance(this.Owner.Center, toEvaluate.TargetPlanet.Position) < radius)
                                {
                                    using (List<ShipModule>.Enumerator enumerator = this.Owner.BombBays.GetEnumerator())
                                    {
                                        while (enumerator.MoveNext())
                                        {
                                            ShipModule current = enumerator.Current;
                                            if ((double)current.BombTimer <= 0.0)
                                            {
                                                Bomb bomb = new Bomb(new Vector3(this.Owner.Center, 0.0f), this.Owner.loyalty);
                                                bomb.WeaponName = current.BombType;
                                                if ((double)this.Owner.Ordinance > (double)ResourceManager.WeaponsDict[current.BombType].OrdinanceRequiredToFire)
                                                {
                                                    this.Owner.Ordinance -= ResourceManager.WeaponsDict[current.BombType].OrdinanceRequiredToFire;
                                                    bomb.SetTarget(toEvaluate.TargetPlanet);
                                                    //lock (GlobalStats.BombLock)
                                                        ArtificialIntelligence.universeScreen.BombList.Add(bomb);
                                                    current.BombTimer = ResourceManager.WeaponsDict[current.BombType].fireDelay;
                                                }
                                            }
                                        }
                                        break;
                                    }
                                }
                                else
                                    break;
                            }
                            else if (this.Owner.HasTroopBay || (this.Owner.hasTransporter))
                            {
                                this.State = AIState.AssaultPlanet;
                                this.OrderAssaultPlanet(target);
                            }
                            else
                                this.OrderQueue.Clear();
                            break;

                        case ArtificialIntelligence.Plan.Exterminate:
                            {
                                this.DoOrbit(toEvaluate.TargetPlanet, elapsedTime);
                                radius = toEvaluate.TargetPlanet.ObjectRadius + this.Owner.Radius + 1000;
                                if (toEvaluate.TargetPlanet.Owner == this.Owner.loyalty || toEvaluate.TargetPlanet.Owner == null)
                                {
                                    this.OrderQueue.Clear();
                                    this.OrderFindExterminationTarget(true);
                                    return;
                                }
                                else
                                {
                                    if (Vector2.Distance(this.Owner.Center, toEvaluate.TargetPlanet.Position) >= radius)
                                        break;
                                    List<ShipModule>.Enumerator enumerator1 = this.Owner.BombBays.GetEnumerator();
                                    try
                                    {
                                        while (enumerator1.MoveNext())
                                        {
                                            ShipModule mod = enumerator1.Current;
                                            if (mod.BombTimer > 0f)
                                                continue;
                                            Bomb b = new Bomb(new Vector3(this.Owner.Center, 0f), this.Owner.loyalty)
                                            {
                                                WeaponName = mod.BombType
                                            };
                                            if (this.Owner.Ordinance <= ResourceManager.WeaponsDict[mod.BombType].OrdinanceRequiredToFire)
                                            {
                                                continue;
                                            }
                                            Ship owner1 = this.Owner;
                                            owner1.Ordinance = owner1.Ordinance - ResourceManager.WeaponsDict[mod.BombType].OrdinanceRequiredToFire;
                                            b.SetTarget(toEvaluate.TargetPlanet);
                                            //lock (GlobalStats.BombLock)
                                            {
                                                ArtificialIntelligence.universeScreen.BombList.Add(b);
                                            }
                                            mod.BombTimer = ResourceManager.WeaponsDict[mod.BombType].fireDelay;
                                        }
                                        break;
                                    }
                                    finally
                                    {
                                        ((IDisposable)enumerator1).Dispose();
                                    }
                                }
                            }
                        case ArtificialIntelligence.Plan.RotateToFaceMovePosition:
                            {
                                this.RotateToFaceMovePosition(elapsedTime, toEvaluate);
                                break;
                            }
                        case ArtificialIntelligence.Plan.RotateToDesiredFacing:
                            {
                                this.RotateToDesiredFacing(elapsedTime, toEvaluate);
                                break;
                            }
                        case ArtificialIntelligence.Plan.MoveToWithin1000:
                            {
                                this.MoveToWithin1000(elapsedTime, toEvaluate);
                                break;
                            }
                        case ArtificialIntelligence.Plan.MakeFinalApproachFleet:
                            {
                                if (this.Owner.fleet != null)
                                {
                                    this.MakeFinalApproachFleet(elapsedTime, toEvaluate);
                                    break;
                                }
                                else
                                {
                                    this.State = AIState.AwaitingOrders;
                                    break;
                                }
                            }
                        case ArtificialIntelligence.Plan.MoveToWithin1000Fleet:
                            {
                                if (this.Owner.fleet != null)
                                {
                                    this.MoveToWithin1000Fleet(elapsedTime, toEvaluate);
                                    break;
                                }
                                else
                                {
                                    this.State = AIState.AwaitingOrders;
                                    break;
                                }
                            }
                        case ArtificialIntelligence.Plan.MakeFinalApproach:
                            {
                                this.MakeFinalApproach(elapsedTime, toEvaluate);
                                break;
                            }
                        case ArtificialIntelligence.Plan.RotateInlineWithVelocity:
                            {
                                this.RotateInLineWithVelocity(elapsedTime, toEvaluate);
                                break;
                            }
                        case ArtificialIntelligence.Plan.StopWithBackThrust:
                            {
                                this.StopWithBackwardsThrust(elapsedTime, toEvaluate);
                                break;
                            }
                        case ArtificialIntelligence.Plan.Orbit:
                            {
                                this.DoOrbit(toEvaluate.TargetPlanet, elapsedTime);
                                break;
                            }
                        case ArtificialIntelligence.Plan.Colonize:
                            {
                                this.Colonize(toEvaluate.TargetPlanet);
                                break;
                            }
                        case ArtificialIntelligence.Plan.Explore:
                            {
                                this.DoExplore(elapsedTime);
                                break;
                            }
                        case ArtificialIntelligence.Plan.Rebase:
                            {
                                this.DoRebase(toEvaluate);
                                break;
                            }
                        case ArtificialIntelligence.Plan.DefendSystem:
                            {
                                if (this.Target != null)
                                    System.Diagnostics.Debug.WriteLine(this.Target);
                                this.DoSystemDefense(elapsedTime);
                                break;
                            }
                        case ArtificialIntelligence.Plan.DoCombat:
                            {
                                this.DoCombat(elapsedTime);
                                break;
                            }
                        case ArtificialIntelligence.Plan.MoveTowards:
                            {
                                this.MoveTowardsPosition(this.MovePosition, elapsedTime);
                                break;
                            }
                        case ArtificialIntelligence.Plan.PickupPassengers:
                            {
                                if (this.start != null)
                                    this.PickupPassengers();
                                else
                                    this.State = AIState.AwaitingOrders;
                                break;
                            }
                        case ArtificialIntelligence.Plan.DropoffPassengers:
                            {

                                try
                                {
                                    this.DropoffPassengers();
                                }
                                catch
                                {
                                    System.Diagnostics.Debug.WriteLine("DropoffPassengers failed");

                                }
                                break;
                            }
                        case ArtificialIntelligence.Plan.DeployStructure:
                            {
                                this.DoDeploy(toEvaluate);
                                break;
                            }
                        case ArtificialIntelligence.Plan.PickupGoods:
                            {
                                try
                                {
                                    this.PickupGoods();
                                }
                                catch
                                { }
                                break;
                            }
                        case ArtificialIntelligence.Plan.DropOffGoods:
                            {
                                this.DropoffGoods();
                                break;
                            }
                        case ArtificialIntelligence.Plan.ReturnToHangar:
                            {
                                this.DoReturnToHangar(elapsedTime);
                                break;
                            }
                        case ArtificialIntelligence.Plan.TroopToShip:
                            {
                                this.DoTroopToShip(elapsedTime);
                                break;
                            }
                        case ArtificialIntelligence.Plan.BoardShip:
                            {
                                this.DoBoardShip(elapsedTime);
                                break;
                            }
                        case ArtificialIntelligence.Plan.SupplyShip:
                            {
                                this.DoSupplyShip(elapsedTime, toEvaluate);
                                break;
                            }
                        case ArtificialIntelligence.Plan.Refit:
                            {
                                this.DoRefit(elapsedTime, toEvaluate);
                                break;
                            }
                        case ArtificialIntelligence.Plan.LandTroop:
                            {
                                this.DoLandTroop(elapsedTime, toEvaluate);
                                break;
                            }
                    }
                }
                goto Label0;
            #if !DEBUG
            }

            catch

            {
            }
            #endif
            Label0:
            AIState aIState = this.State;
            if (aIState == AIState.SystemTrader)
            {
                foreach (ArtificialIntelligence.ShipGoal goal in this.OrderQueue)
                {

                    if (goal.Plan == ArtificialIntelligence.Plan.TransportPassengers && goal.TargetPlanet != null && goal.TargetPlanet.Owner != this.Owner.loyalty)
                    {
                        this.OrderQueue.Clear();
                        this.State = AIState.AwaitingOrders;
                        break;
                    }
                    else if (goal.Plan == ArtificialIntelligence.Plan.PickupPassengers && goal.TargetPlanet != null && goal.TargetPlanet.Owner != this.Owner.loyalty)
                    {
                        this.OrderQueue.Clear();
                        this.State = AIState.AwaitingOrders;
                        break;
                    }
                    else if (goal.Plan == ArtificialIntelligence.Plan.PickupGoods && goal.TargetPlanet != null && goal.TargetPlanet.Owner != this.Owner.loyalty)
                    {
                        this.OrderQueue.Clear();
                        this.State = AIState.AwaitingOrders;
                        break;
                    }
                    else if (goal.Plan != ArtificialIntelligence.Plan.DropoffPassengers || goal.TargetPlanet == null || goal.TargetPlanet.Owner == this.Owner.loyalty)
                    {
                        if (goal.Plan != ArtificialIntelligence.Plan.DropOffGoods || goal.TargetPlanet == null || goal.TargetPlanet.Owner == this.Owner.loyalty)
                        {
                            continue;
                        }
                        this.OrderQueue.Clear();
                        this.State = AIState.AwaitingOrders;
                        break;
                    }
                    else
                    {
                        this.OrderQueue.Clear();
                        this.State = AIState.AwaitingOrders;
                        break;
                    }
                }
            }
            else if (aIState == AIState.PassengerTransport)
            {
                foreach (ArtificialIntelligence.ShipGoal goal in this.OrderQueue)
                {
                    if (goal.Plan == ArtificialIntelligence.Plan.TransportPassengers && goal.TargetPlanet != null && goal.TargetPlanet.Owner != this.Owner.loyalty)
                    {
                        this.OrderQueue.Clear();
                        this.State = AIState.AwaitingOrders;
                        break;
                    }
                    else if (goal.Plan == ArtificialIntelligence.Plan.PickupPassengers && goal.TargetPlanet != null && goal.TargetPlanet.Owner != this.Owner.loyalty)
                    {
                        this.OrderQueue.Clear();
                        this.State = AIState.AwaitingOrders;
                        break;
                    }
                    else if (goal.Plan == ArtificialIntelligence.Plan.PickupGoods && goal.TargetPlanet != null && goal.TargetPlanet.Owner != this.Owner.loyalty)
                    {
                        this.OrderQueue.Clear();
                        this.State = AIState.AwaitingOrders;
                        break;
                    }
                    else if (goal.Plan != ArtificialIntelligence.Plan.DropoffPassengers || goal.TargetPlanet == null || goal.TargetPlanet.Owner == this.Owner.loyalty)
                    {
                        if (goal.Plan != ArtificialIntelligence.Plan.DropOffGoods || goal.TargetPlanet == null || goal.TargetPlanet.Owner == this.Owner.loyalty)
                        {
                            continue;
                        }
                        this.OrderQueue.Clear();
                        this.State = AIState.AwaitingOrders;
                        break;
                    }
                    else
                    {
                        this.OrderQueue.Clear();
                        this.State = AIState.AwaitingOrders;
                        break;
                    }
                }
            }
            else if (aIState == AIState.Rebase)
            {
                foreach (ArtificialIntelligence.ShipGoal goal in this.OrderQueue)
                //Parallel.ForEach(this.OrderQueue, (goal, state) =>
                {
                    if (goal.Plan != ArtificialIntelligence.Plan.Rebase || goal.TargetPlanet == null || goal.TargetPlanet.Owner == this.Owner.loyalty)
                    {
                        continue;
                    }
                    this.OrderQueue.Clear();
                    this.State = AIState.AwaitingOrders;
                    break;
                }
            }
            //if(targetChangeTimer >-1)
            //targetChangeTimer -= elapsedTime;
            //if(TriggerDelay >-1)
            TriggerDelay -= elapsedTime;
            if (this.Owner.InCombat && this.BadGuysNear && !this.IgnoreCombat)
            {
                if (this.TriggerDelay < 0)
                {
                    TriggerDelay = elapsedTime * 2;
                    bool docombat = false;
                    LinkedListNode<ArtificialIntelligence.ShipGoal> tempShipGoal = this.OrderQueue.First;
                    ShipGoal firstgoal = tempShipGoal != null ? tempShipGoal.Value : null;  //.FirstOrDefault<ArtificialIntelligence.ShipGoal>();
                    if (this.Owner.Weapons.Count > 0 || this.Owner.GetHangars().Count > 0)
            #if !DEBUG
                        try
            #endif
                    {

                        docombat = (!this.HasPriorityOrder && (this.OrderQueue.Count == 0 || firstgoal != null && firstgoal.Plan != ArtificialIntelligence.Plan.DoCombat));

                        if (docombat)//|| this.OrderQueue.Count == 0))
                        {
                            this.OrderQueue.AddFirst(new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.DoCombat, Vector2.Zero, 0f));
                        }

                        //this.fireTask = Task.Factory.StartNew(this.FireOnTarget);//,TaskCreationOptions.LongRunning);
                        //fireTask = new Task(this.FireOnTarget);
                        this.FireOnTarget();

                    }

            #if !DEBUG
                        catch
                        {
                        }

            #endif
                }
            }
            else
            {
                if (this.Owner.GetHangars().Count > 0 && this.Owner.loyalty != ArtificialIntelligence.universeScreen.player)
                {
                    foreach (ShipModule hangar in this.Owner.GetHangars())
                    {
                        if (hangar.IsTroopBay || hangar.IsSupplyBay || hangar.GetHangarShip() == null
                            //||hangar.GetHangarShip().InCombat
                            || hangar.GetHangarShip().GetAI().State == AIState.ReturnToHangar)
                        {
                            continue;
                        }
                        hangar.GetHangarShip().GetAI().OrderReturnToHangar();
                    }
                }
                else if (this.Owner.GetHangars().Count > 0)
                {
                    foreach (ShipModule hangar in this.Owner.GetHangars())
                    {
                        if (hangar.IsTroopBay
                            || hangar.IsSupplyBay
                            || hangar.GetHangarShip() == null
                            || hangar.GetHangarShip().GetAI().State == AIState.ReturnToHangar
                            //|| hangar.GetHangarShip().InCombat
                            || hangar.GetHangarShip().GetAI().hasPriorityTarget
                            || hangar.GetHangarShip().GetAI().HasPriorityOrder

                            )
                        {
                            continue;
                        }
                        hangar.GetHangarShip().DoEscort(this.Owner);
                    }
                }
            }
            if (this.State == AIState.Resupply && !this.HasPriorityOrder)
            {
                this.HasPriorityOrder = true;
            }
            //if (this.Owner.Weapons.Count() == 0 && this.BadGuysNear) //||( this.State != AIState.AssaultPlanet && this.State != AIState.Boarding
            //{
            //    this.CombatState = Gameplay.CombatState.Evade;
            //}
            if (!this.Owner.isTurning)
            {
                this.DeRotate();
                return;
            }
            else
            {
                return;
            }
        }