function FireEnemyGunsTB(%id, %side)
{
//   echo("FIRE ENEMY GUNS " @ %id);
   
   switch$ (%side)
   {
      case "front":
         %count = getWordCount(%id.fronttargets);
         %player = getWord(%id.fronttargets, getRandom(0, %count-1));  
         %id.front = true;    
      case "back":
         %count = getWordCount(%id.backtargets);
         %player = getWord(%id.backtargets, getRandom(0, %count-1));      
         %id.back = true;    
      case "right":
         %count = getWordCount(%id.righttargets);
         %player = getWord(%id.righttargets, getRandom(0, %count-1));      
         %id.right = true;    
      case "left":
         %count = getWordCount(%id.lefttargets);
         %player = getWord(%id.lefttargets, getRandom(0, %count-1));      
         %id.left = true;    
   }
   
   if(%id.ammo > 0)   
      AudioFireGunsLow();
   else
      alxPlay(crossbow2low);   

   %firecapacity = GetVehicleFiringCapacity($Enemyvehicles[%id.slot, vehicle], %side);
   
   %maxfire = getWordCount(%id.crew)-%id.crewfired;
   
   if(%maxfire > %firecapacity)
      %maxfire = %firecapacity;
                     
   for(%i=1;%i<=%maxfire;%i++)
   {
      %location = getRandom(1, 6);
      EnemyGunRoll(%id, %player.slot, %location);
      %id.crewfired++;
      
      if(%id.ammo > 0)
      {      
         if(%id.trailer !$= "")
         {
            switch$ (%side)
            {
               case "front":
                  schedule(getRandom(50, 500), 0, "CreateFrontGunFire", %id.trailer);
               case "back":
                  schedule(getRandom(50, 500), 0, "CreateBackGunFire", %id.trailer);
               case "right":
                  schedule(getRandom(50, 500), 0, "CreateRightGunFire", %id.trailer);
               case "left":
                  schedule(getRandom(50, 500), 0, "CreateLeftGunFire", %id.trailer);
            }
         }
         else
         {
            switch$ (%side)
            {
               case "front":
                  schedule(getRandom(50, 500), 0, "CreateFrontGunFire", %id);
               case "back":
                  schedule(getRandom(50, 500), 0, "CreateBackGunFire", %id);
               case "right":
                  schedule(getRandom(50, 500), 0, "CreateRightGunFire", %id);
               case "left":
                  schedule(getRandom(50, 500), 0, "CreateLeftGunFire", %id);
            }
         }
      }
   }                     
   
//   echo("END FIRE ENEMY GUNS " @ %id);
      
   schedule($ClearToFireSide, 0, "ClearSide", %id, %side);   
   schedule($ClearToFireguns, 0, "ClearToFireGuns", %id, %maxfire);   
}


/* 
the basic system is like this - each area of the vehicle has a base defense and then a possible bonus
for armor. if a hit is scored the armor takes damage and the sub-system takes damage. If not hit
is scored the armor still takes damage but no damage to the sub system
*/
 
function EnemyGunRollTB(%id, %slot, %location)
{
   // this is a barrage of fire so if the vehicle gets destroyed during the barrage and there are still
   // more shots to be fired
   
   if($vehicles[%slot, battleid] $= "")
      return;

   // decide which area this soldier is firing at
   
   %rand = getRandom(1, 6);
   
   // qualify tire attack, if the opposing vehicle doesn't have any tires left don't bother shooting
   
   if(%rand == 3)
   {
      %name = $vehicles[%slot, vehicle];
      %maxtires = GetMaxVehicleTires(%name);
      
      // if they have all their tires blown out then just do a vehicle or people attack
      
      if($vehicles[%slot, badtires] $= %maxtires)
         %rand = getRandom(1, 2);         
   }

   // if the engine is gone don't fire at it anymore
   
   if(%rand == 5)
   {
      if($vehicles[%slot, currentenginehp] == 0)
         %rand = getRandom(1, 2);         
   }
   
   // if there is no mounted weapon choose another location
   
   if(%rand == 6)
   {
      if($vehicles[%slot, mountedweapon] $= "")
         %rand = getRandom(1, 2);                  
   }
   
   switch$ (%rand)
   {
      case 1:
         %area = "vehicle";
         %defense = GetArmorClass($vehicles[%slot, vehicle]);
         %bonus = GetArmorBonus($vehicles[%slot, currentarmor]);
      case 2:
         %area = "people";
         %defense = GetArmorClass("window");
         %bonus = GetArmorBonus($vehicles[%slot, currentwindowarmor]);
      case 3:   
         %area = "tires";
         %defense = GetArmorClass("tires");
         %bonus = GetArmorBonus($vehicles[%slot, currenttirearmor]);
      case 4:
         %area = "gastank";
         %defense = GetArmorClass("gastank");
         %bonus = GetArmorBonus($vehicles[%slot, currentgastankarmor]);
      
      // engine uses the vehicle armor
      
      case 5:
         %area = "engine";
         %defense = GetArmorClass($vehicles[%slot, vehicle]);
         %bonus = GetArmorBonus($vehicles[%slot, currentarmor]);
         
      // this is the exception, if the vehicle doesn't have a mounted weapon the shot will go 
      // for people
      
      case 6:
         %area = "mountedweapon";
         %defense = GetArmorClass("mountedweapon");
   }
   
   %defense = %defense+%bonus;

   %attack = getRandom(1, 20);

   switch$ ($Difficulty)
   {
      case "easy":
         %attack--;
      case "hard":      
         %attack++;
   }
   
   // get the soldier that is doing the firing and add firing bonus if any
   
   %count = getWordCount(%id.crew);

   %soldier = getWord(%id.crew, getRandom(0, %count-1));
   
   // decide if they are firing a gun or crossbow
   
   if(%weaponsfired <= %id.guns && %id.ammo > 0)
      %id.ammo--;
   else
      %attack = %attack-2;

   // factor in mods
   
   %playervehicle = $vehicles[%slot, vehicle];
   %attack = %attack+GetSizeAttackMod(%playervehicle);

   %playerid = $vehicles[%slot, battleid];
   %attack = %attack+GetSpeedAttackMod(%id.currentspeed, %playerid.currentspeed);

   // range mod
   
   %distance = VectorDist(%id.GetPosition(), %playerid.GetPosition());
   
   if(%distance <= 40)
      %attack++;
      
   if(%distance >= 80)
      %attack--;

   // 1 is an auto miss
   
//   echo("enemy attack " @ %attack SPC %defense);
   
   if(%attack > 1)
   {
      // 20 is an auto hit
      
      if(%attack >= 20)
      {
         %hit = true;
         %damage = GetGunDamage();         
      }
      else
      {
         
         if(%attack >= %defense)
         {
            %hit = true;
            %damage = GetGunDamage();         
//            echo("enemy hit" SPC %area);
         }
      }
   }

   
   if(%hit $= true)
   {
      schedule(getRandom(100, 500), 0, "CreateVehicleHits", %id);
      
      switch$ (%area)
      {
         case "vehicle":
//               echo("Enemy Vehicle Attack");
            if($vehicles[%slot, currentarmor] > 0)
            {
               $vehicles[%slot, currentarmor] = $vehicles[%slot, currentarmor]-%damage;
               
               if($vehicles[%slot, currentarmor] < 0)
                  $vehicles[%slot, currentarmor] = 0;
                  
               %roll = getRandom(1, 20);
            }

            if($vehicles[%slot, currentarmor] == 0 || %roll == 20)
            {
               $vehicles[%slot, currentvehiclehp] = $vehicles[%slot, currentvehiclehp]-%damage;

               UpdateHealthBar($vehicles[%slot, battleid]);

               // vehicle is destroyed
               
               if($vehicles[%slot, currentvehiclehp] <= 0)
               {
                  echo("PLAYER VEHICLE DESTROYED BY VEHICLE ATTACK");
                  DestroyPlayerVehicle($vehicles[%slot, battleid]); 
               }
            }
               
         case "people":
//               echo("Enemy People Attack");
            if($vehicles[%slot, currentwindowarmor] > 0)
            {
               $vehicles[%slot, currentwindowarmor] = $vehicles[%slot, currentwindowarmor]-%damage;

               if($vehicles[%slot, currentwindowarmor] > 0)
                  $vehicles[%slot, currentwindowarmor] = 0;
                  
               %roll = getRandom(1, 20);
            }

            if($vehicles[%slot, currentwindowarmor] == 0 || %roll == 20)
            {
               // randomly select someone to kill
                              
               %val = trim($vehicles[%slot, battleid].crew);
               $vehicles[%slot, battleid].crew = RemoveWord(%val, 0);                     
               
               // if the player vehicle has less than 10% crew left start to flash the health bar
               
               %count = getWordCount($vehicles[%slot, battleid].crew);
               
               %capacity = GetVehiclePeopleCapacity($vehicles[%slot, battleid].vehiclename);
               
               %min = %capacity / 10;
               
               if(%count < %min)
                  FlashPlayerHealthBar($vehicles[%slot, battleid]);
                  
               // after someone is killed check to see if that was the last person in the vehicle
               
               if(getWordCount($vehicles[%slot, battleid].crew) == 0)
               {
                  echo("PLAYER VEHICLE DESTROYED BY PEOPLE ATTACK");
                  StopPlayerVehicle($vehicles[%slot, battleid]); 
               }
            }

         case "tires":   
//               echo("Enemy Tire Attack");
            if($vehicles[%slot, currenttirearmor] > 0)
            {
               $Vehicles[%slot, currenttirearmor] = $Vehicles[%slot, currenttirearmor]-%damage;

               if($Vehicles[%slot, currenttirearmor] > 0)
                  $Vehicles[%slot, currenttirearmor] = 0;
                  
               %roll = getRandom(1, 20);
            }
            
            if($Vehicles[%slot, currenttirearmor] == 0 || %roll == 20)
            {
               // if they have upgraded tires there is a chance it will withstand the shot
               
               if($Vehicles[%slot, tireupgrades] > 0)
               {
                  %rand = getRandom(1, 10);
                  
                  if(%rand <= $Vehicles[%slot, tireupgrades])
                     %miss = true;
               }
               
               if(%miss $= "")
               {
                  // knock out a tire
                  
                  if($Vehicles[%slot, badtires] < $Vehicles[%slot, tires])
                     $Vehicles[%slot, badtires]++;
                  
                  AdjustSpeedWithBadTires($Vehicles[%slot, battleid]);
               }
            }
                        
         case "gastank":
//               echo("Enemy gastank Attack");               
            if($vehicles[%slot, currentgastankarmor] > 0)
            { 
               $Vehicles[%slot, currentgastankarmor] = $Vehicles[%slot, currentgastankarmor]-%damage;

               if($Vehicles[%slot, currentgastankarmor] < 0)
                  $Vehicles[%slot, currentgastankarmor] = 0;
               
               %roll = getRandom(1, 100);
            }
            
            if($vehicles[%slot, currrentgastankarmor] == 0 || %roll == 100 && $vehicles[%slot, battleid].gastankexplosion $= "")
            {
               %roll = getRandom(1, 300);
               
               if(%roll >= 298)
               {
                  CreateGasTankFire($vehicles[%slot, battleid]);
                  %time = getRandom(60000, 180000);                  
                  $vehicles[%slot, battleid].gastankexplosion = schedule(%time, 0, "DestroyPlayerVehicle", $vehicles[%slot, battleid]);                               
                  
                  %time = %time-1000;
                  
                  schedule(%time, 0, "PutGasTankFireOut", $vehicles[%slot, battleid]); 
               }               
            }
            
         case "engine":
//                echo("Enemy Engine Attack");
           if($vehicles[%slot, currentearmor] > 0)
            {
               $Vehicles[%slot, currentarmor] = $Vehicles[%slot, currentarmor]-%damage;

               if($Vehicles[%slot, currentarmor] > 0)
                  $Vehicles[%slot, currentarmor] = 0;
                  
               %roll = getRandom(1, 20);
            }
            

            if($Vehicles[%slot, currentarmor] == 0 || %roll == 20)
            {
               // damage the engine

               $Vehicles[%slot, currentenginehp] = $Vehicles[%slot, currentenginehp]-%damage;

               if($Vehicles[%slot, currentenginehp] < 0)
               {
                  $Vehicles[%slot, currentenginehp] = 0;
                  $vehicles[%slot, battleid].blownengine = true;
                  $vehicles[%slot, battleid].SetAtRest();                                    
               }
            }
            
         case "mountedweapon":
//               echo("Enemy mounted Attack");
            $Vehicles[%slot, currentmountedweaponhp] = $Vehicles[%slot, currentmountedweaponhp]-%damage;

            // weapon is destroyed               
            if($Vehicles[%slot, currentmountedweaponhp] < 0)
            {
               $Vehicles[%slot, mountedweapon] = "";
               $Vehicles[%slot, stockmountedweaponhp] = "";
               $Vehicles[%slot, currentmountedweaponhp] = "";

               // add code here to remove mounted weapon on vehicle

               CreateMountedWeaponFire($vehicles[%slot, battleid]);               
               $vehicles[%slot, battleid].special.Delete();
               $vehicles[%slot, battleid].special = "";               
               
            }
         }
   }
   
//   echo("Done Firing Enemy Guns");
   
   schedule($ClearToFireguns, 0, "ClearToFireGuns", %id, %side);   
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////// special weapons //////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function FireEnemySpecialWeaponTB(%id, %player)
{
   switch$($Enemyvehicles[%id.slot, mountedweapon])
   {
      case "flamethrower":               
         if(Screen2D.getIsWindowPoint(%id.GetPosition()) $= true)   
            alxPlay(Flamer);               

         CreateFlameThrower(%id);         
         EnemySpecialWeaponRoll(%id, %player);

         %id.specialclearfire = true;
         schedule(6000, 0, "ClearSpecialWeapon", %id);
      case "machinegun":
         AudioFireGunsLow();

         CreateMachineGunMuzzle(%id);         
         EnemySpecialWeaponRoll(%id, %player);

         %id.specialclearfire = true;
         schedule(5000, 0, "ClearSpecialWeapon", %id);
     case "crossbow":         
            CreateEnemyVehicleCrossbow(%id, %player);
            %id.specialclearfire = true;
            schedule(2000, 0, "ClearSpecialWeapon", %id);
      case "rpg":   
         %id.specialclearfire = true;
         schedule(8000, 0, "ClearSpecialWeapon", %id);

         if(Screen2D.getIsWindowPoint(%id.GetPosition()) $= true)   
            alxPlay(RPGFiring);               

         CreateRpgMuzzle(%id);                                       
         schedule(250, 0, "EnemySpecialWeaponRoll", %id, %player);
   }
}

// as of now a special weapon will only inflict damage on the vehicle itself, logic being it can't be aimed to a specific 
// location

function EnemySpecialWeaponRollTB(%id, %target)
{  
   if($Enemyvehicles[%id.slot, mountedweapon] $= "rpg")
      CreateRpgExplosion(%target);
      
   %defense = GetArmorClass($vehicles[%target.slot, vehicle]);
   %bonus = GetArmorBonus($vehicles[%target.slot, currentarmor]);
   
   %defense = %defense+%bonus;
      
   // range mod - flame throwers don't get a distance mod
   
   if($Enemyvehicles[%id.slot, mountedweapon] !$= "flamethrower")
   {
      %dist = VectorDist(%id, %target);
      
      if(%dist <= 30)
         %bonus = 1;      
   }
   
   // flame throwers get a huge bonus to hit
   
   if($Enemyvehicles[%id.slot, mountedweapon] $= "flamethrower")
      %bonus = 4;
   
   // deduct ammo - 4 ammo for the attack   
   
   switch$ ($Enemyvehicles[%id.slot, mountedweapon])
   {
      case "crossbow":
         %id.ammo = %id.ammo-2;      
      case "flamethrower":
         %id.ammo = %id.ammo-4;      
      case "machinegun":
         %id.ammo = %id.ammo-5;      
      case "rpg":      
         %id.ammo = %id.ammo-6;
   }   
   
   // the attack
   
   %attack = getRandom(1, 20);

   switch$ ($Difficulty)
   {
      case "easy":
         %attack--;
      case "hard":      
         %attack++;
   }
   
   %attack = %attack+%bonus;
   
   // factor in mods
   
   %attack = %attack+GetSizeAttackMod($Enemyvehicles[%target.slot, vehicle]);
   
   %attack = %attack+GetSpeedAttackMod(%id.currentspeed, %id.target.currentspeed);
   
   
   if(%attack >= %defense)
   {       
      %damage = GetSpecialWeaponDamage($Enemyvehicles[%id.slot, mountedweapon]); 

      if($vehicles[%target.slot, currentarmor] > 0)
      {
         $vehicles[%target.slot, currentarmor] = $vehicles[%target.slot, currentarmor]+%damage;
         
         if($vehicles[%target.slot, currentarmor] > 0)
            $vehicles[%target.slot, currentarmor] = 0;
            
         %roll = getRandom(1, 20);
      }
      
      if($vehicles[%target.slot, currentarmor] == 0 || %roll == 20)
         $vehicles[%target.slot, currentvehiclehp] = $vehicles[%target.slot, currentvehiclehp]-%damage;
      
      // vehicle is destroyed
      
      if($vehicles[%target.slot, currentvehiclehp] <= 0)
      {
         echo("PLAYER VEHICLE DESTROYED BY SPECIAL WEAPON");
         DestroyPlayerVehicle(%target); 
      }

      if($vehicles[%id.slot, mountedweapon] $= "flamethrower")
      {
         %sprite = new t2dAnimatedSprite()
         {
            scenegraph = "sg";  
            size = "3 5.6";
         };
         
         %sprite.PlayAnimation(smolderingfire2Animation, true, 0, false);
         %sprite.mount(%target, "0 0", 0, true, true, true, true);   
         %id.firedamagesprite = %sprite;            

         schedule(3000, 0, "CausePlayerFireDamage", %target);      
      }

      echo("WEAPON DAMAGE " @ %damage);
      UpdateHealthBar(%target);
   }
}


// when hit by a flame thrower it will continue to cause damage

function CausePlayerFireDamageTB(%target)
{
   if($vehicles[%target.slot, battleid] $= "")
      return;
   
   if(%target.firedamageturns == 3)
   {
      %target.firedamagesprite.SafeDelete();
      return;
   }
            
   // if this is the first fire damage put a flame on it
         
   %damage = getRandom(1, 4);   

   if($vehicles[%target.slot, currentarmor] > 0)
   {
      $vehicles[%target.slot, currentarmor] = $vehicles[%target.slot, currentarmor]-%damage;
      
      if($vehicles[%target.slot, currentarmor] < 0)
         $vehicles[%target.slot, currentarmor] = 0;
         
      %roll = getRandom(1, 20);
   }
   
   if($vehicles[%target.slot, currentarmor] == 0 || %roll == 20)
      $vehicles[%target.slot, currentvehiclehp] = $vehicles[%target.slot, currentvehiclehp]-%damage;
   
   // vehicle is destroyed
   
   if($vehicles[%target.slot, currentvehiclehp] <= 0)
   {
      echo("PLAYER VEHICLE DESTROYED BY SPECIAL WEAPON");
      DestroyPlayerVehicle(%target); 
   }
   else
   {         
      %target.firedamageturns++;   
      
      UpdateHealthBar(%target);
      
      schedule(3000, 0, "CausePlayerFireDamage", %target);
   }
}

function PickPlayerTargetTB(%slot)
{
   %id = $enemyvehicles[%slot, battleid];
   %lowestdist = 10000;
   
   for(%i=1;%i<=10;%i++)
   {
      if($vehicles[%i, battleid] !$= "")
      {
         %dist = VectorDist($vehicles[%i, battleid].GetPosition(), $enemyvehicles[%slot, battleid].GetPosition());   
         
         if(%dist < %lowestdist)
         {
            $enemyvehicles[%slot, battleid].target = $vehicles[%i, battleid];          
            %lowestdist = %dist;
         }
      }
   }
}