function StartPeopleBattle()
{
   SaveSpecialLocationsToTemp();
   SaveNukesToTemp();
   
   UpdateTime();
   
   %list = sg.PickPoint(player.GetPosition());

   %count = getWordCount(%list);
   
   for(%i=0;%i<%count;%i++)
   {
      %obj = getWord(%list, %i);

      if(%obj.tilemap $= "" && %obj.spawn $= "")
      {      
         if(%obj.city !$= "")
            %map = 11;
         if(%obj.GetImageMap() $= "skinnyroad1imagemap")
            %map = 12;
         if(%obj.GetImageMap() $= "skinnyroad1_1imagemap")
            %map = 12;
      }
   }
   
   if(%map $= "")
      %map = 10;

   canvas.SetContent(LoadingScreen);
   canvas.CursorOff();
   ResetLoadingBar();
   ChangeLoadingBar(200);
   
   $combat = true;   
   $peoplebattle = true;
   
   $EnemySoldierList = "";
   $playerSoldierList = "";
   $peopleBattleVehicles = "";
   $DeadSoldiers = "";
   $peopleCounter = 0;
   $CurrentSquad = 1;
   $pause = "";
         
   deleteVariables("$PlayerSquad*");
   
   // clear out the spawn markers
   
   p1.taken = "";
   p2.taken = "";
   p3.taken = "";
   p4.taken = "";
   p5.taken = "";
   p6.taken = "";
   p7.taken = "";
   
   // enemy squads

   deleteVariables("$EnemySquad*");

   // clear out enemy spawn markers
         
   e1.taken = "";
   e2.taken = "";
   e3.taken = "";
   e4.taken = "";
   e5.taken = "";

   alxStop($Wind);
            
   $lastCombat = $mastertime;
   
   PeopleBattle.Visible = true;
   mainbar.Visible = false;
   Infowindow.Visible = false;   // if the player was actually attacked, the info window will stay up
   InfantryRetreatButton.SetText("Retreat");

   // pick a battlefield at random, if the player is on a city tile then only choose the city map
   
   $playerPosition = player.getPosition();
   $PlayerFacing = player.facing;
   
   schedule(500, 0, "PrepPeopleBattle", %map);     
}

function PrepPeopleBattle(%map)
{
   ChangeLoadingBar(200);

   switch$ (%map)
   {
      case 10:
         Screen2D.loadLevel(expandFilename("~/data/levels/battle10.t2d"));
      case 11:
         Screen2D.loadLevel(expandFilename("~/data/levels/battle11.t2d"));
      case 12:
         Screen2D.loadLevel(expandFilename("~/data/levels/battle12.t2d"));
   }
   
   schedule(500, 0, "BeginPeopleBattle", %map);    
   
   $InfantryMap = %map; 
   
   setAcceptableScreenInfantryRatio();
}

// set the stage for the battle, the firing starts here

function BeginPeopleBattle(%map)
{         
   %x = 0;
   %y = 0;
            
   %vehiclestart = %y+5;
   %propstart = %y-20;
   
   BuildEnemySoldiers();
   BuildPlayerSoldiers();
   AssignPlayerAmmo();
   AssignEnemyAmmo();
   BuildPlayerProps(%x, %vehiclestart);
   BuildEnemyBattleProps(%x, %propstart, %map);

   canvas.SetContent(MainMap);
   canvas.cursoroff();

   alxPlay(marching);
   
   schedule(7000, 0, "AlxStopAll");
   schedule(8000, 0, "TurnOnInfantryCursor");
   
   %count = getWordCount($PlayerSquad[1, soldiers]);

   for(%i=0;%i<%count;%i++)
   {
      %soldier = getWord($PlayerSquad[1, soldiers], %i);      
      
      %soldier.SetBlending(true, ONE, ONE_MINUS_SRC_ALPHA);            
   }
   
   if($PlayerSquad[1, soldiers] !$= "" && $PlayerSquad[1, ammo] $= "")
      AddPlayerInfantryCrossbowIcons(1);
   if($PlayerSquad[2, soldiers] !$= "" && $PlayerSquad[2, ammo] $= "")
      AddPlayerInfantryCrossbowIcons(2);
   if($PlayerSquad[3, soldiers] !$= "" && $PlayerSquad[3, ammo] $= "")
      AddPlayerInfantryCrossbowIcons(3);
   if($PlayerSquad[4, soldiers] !$= "" && $PlayerSquad[4, ammo] $= "")
      AddPlayerInfantryCrossbowIcons(4);
   if($PlayerSquad[5, soldiers] !$= "" && $PlayerSquad[5, ammo] $= "")
      AddPlayerInfantryCrossbowIcons(5);
   if($PlayerSquad[6, soldiers] !$= "" && $PlayerSquad[6, ammo] $= "")
      AddPlayerInfantryCrossbowIcons(6);
   if($PlayerSquad[7, soldiers] !$= "" && $PlayerSquad[7, ammo] $= "")
      AddPlayerInfantryCrossbowIcons(7);
   
   UpdatePeopleBattleWindow();
   
   DisplayTutorial("InfantryBattle");
   schedule(8000, 0, "PlayerInfantryAI");
   schedule(8000, 0, "EnemyInfantryAi");
}

function UpdatePeopleBattleWindow()
{
   %refuges = 0;
   %brigands = 0;
   %militia = 0;
   %police = 0;
   %soldiers = 0;
   %mercenaries = 0;
   
   %mod = GetPlayerCoverBonus($currentSquad);
   
   if($PlayerSquad[$currentSquad, ammo] $= "")
      %ammo = 0;
   else
      %ammo = $PlayerSquad[$currentSquad, ammo];
         
   %string = $PlayerSquad[$currentSquad, soldiers];
   pb_ammo.setText(%ammo);

   if($PlayerSquad[$currentSquad, timer] $= "")
      pb_position.setText("Position " @ $PlayerSquad[$currentSquad, position]);
   else
      pb_position.setText("Position " @ $PlayerSquad[$currentSquad, position] SPC "(" @ $PlayerSquad[$currentSquad, timer] @ ")");
   
   pb_defense.setText($PlayerSquad[$currentSquad, defensemodifier]+%mod);

   for(%i=0;%i<=4;%i++)
   {
      %soldier = getWord(%string, %i);
      
      if(%soldier !$= "")
      {
         if(%soldier.class $= "refuges")
            %refuges++;
         if(%soldier.class $= "brigands")
            %brigands++;
         if(%soldier.class $= "militia")
            %militia++;
         if(%soldier.class $= "police")
            %police++;
         if(%soldier.class $= "soldiers")
            %soldiers++;
         if(%soldier.class $= "mercenaries")
            %mercenaries++;
      }
   }
      
   pb_refuges.setText(%refuges);
   pb_brigands.setText(%brigands);
   pb_militia.setText(%militia);
   pb_police.setText(%police);
   pb_soldiers.setText(%soldiers);
   pb_mercenaries.setText(%mercenaries);   
}

function RotateInfantrySquad()
{
   greenflag.visible = false;
   
   %count = getWordCount($PlayerSquad[$CurrentSquad, soldiers]);

   for(%i=0;%i<%count;%i++)
   {
      %soldier = getWord($PlayerSquad[$CurrentSquad, soldiers], %i);      
      
      %soldier.SetBlending(true, SRC_ALPHA, ONE_MINUS_SRC_ALPHA);            
   }

   while(%match $= "")
   {
      $CurrentSquad++;
      
      %count = getWordCount($PlayerSquad[$CurrentSquad, soldiers]);
      
      if(%count > 0)
         break;   
      
      if($CurrentSquad > 7)
         $CurrentSquad = 0;     
      
      // this means this function was called on the last soldier dying in the last squad
      
      %counter++;
      
      if(%counter == 10)
         return;
   }
   
   for(%i=0;%i<%count;%i++)
   {
      %soldier = getWord($PlayerSquad[$CurrentSquad, soldiers], %i);      
      
      %soldier.SetBlending(true, ONE, ONE_MINUS_SRC_ALPHA);            
   }
   
   for(%i=1;%i<=4;%i++)
   {
      %count = getWordCount($EnemySquad[%i, soldiers]);
       
      if(%count > 0)
      {
         for(%j=0;%j<%count;%j++)
         {
            %soldier = getWord($EnemySquad[%i, soldiers], %j);            
            %soldier.SetBlending(true, SRC_ALPHA, ONE_MINUS_SRC_ALPHA);            
            %soldier.SetBlendColor(255, 255, 255, 255);
         }
      }
   }
   
   if($PlayerSquad[$CurrentSquad, target] !$= "")
   {      
      %count = getWordCount($EnemySquad[$PlayerSquad[$CurrentSquad, target], soldiers]);
      
      for(%i=0;%i<%count;%i++)
      {
         %soldier = getWord($EnemySquad[$PlayerSquad[$CurrentSquad, target], soldiers], %i);               
         %soldier.SetBlending(true, ONE, ONE_MINUS_SRC_ALPHA);            
         %soldier.SetBlendColor(166, 0, 0, 255);
      }
   }   
   
   %soldier = getWord($PlayerSquad[$CurrentSquad, soldiers], 0);
   
   if(%soldier.dest !$= "")
   {
      greenflag.visible = true;
      greenflag.SetPosition(%soldier.dest);      
   }
   
   UpdatePeopleBattleWindow();
   
   echo("ROTATE INFANTRY CLICK");   
   alxPlay(click);
}

function SelectInfantrySquad(%coords)
{
   greenflag.visible = false;

   %list = sg.PickPoint(%coords);
   
   %count = getWordCount(%list);
   
   for(%i=0;%i<%count;%i++)
   {
      %obj = getWord(%list, %i);
      
      if(%obj.player $= 1)
      {
         %squad = %obj.squad;
         break;
      }
   }
   
   %count = getWordCount($PlayerSquad[$CurrentSquad, soldiers]);

   for(%i=0;%i<%count;%i++)
   {
      %soldier = getWord($PlayerSquad[$CurrentSquad, soldiers], %i);      
      
      %soldier.SetBlending(true, SRC_ALPHA, ONE_MINUS_SRC_ALPHA);            
   }

   while(%match $= "")
   {
      $CurrentSquad++;
      
      %count = getWordCount($PlayerSquad[$CurrentSquad, soldiers]);
      
      if(%count > 0)
         break;   
      
      if($CurrentSquad > 7)
         $CurrentSquad = 0;     
      
      // this means this function was called on the last soldier dying in the last squad
      
      %counter++;
      
      if(%counter == 10)
         return;
   }
   
   $CurrentSquad = %squad;
      
   for(%i=0;%i<%count;%i++)
   {
      %soldier = getWord($PlayerSquad[$CurrentSquad, soldiers], %i);      
      
      %soldier.SetBlending(true, ONE, ONE_MINUS_SRC_ALPHA);            
   }
   
   // reseting the enemy squads if one was a target
      
   for(%i=1;%i<=4;%i++)
   {
      %count = getWordCount($EnemySquad[%i, soldiers]);
       
      if(%count > 0)
      {
         for(%j=0;%j<%count;%j++)
         {
            %soldier = getWord($EnemySquad[%i, soldiers], %j);            
            %soldier.SetBlending(true, SRC_ALPHA, ONE_MINUS_SRC_ALPHA);            
            %soldier.SetBlendColor(255, 255, 255, 255);
         }
      }
   }
   
   // if the player squad has a target
      
   if($PlayerSquad[$CurrentSquad, target] !$= "")
   {      
      %count = getWordCount($EnemySquad[$PlayerSquad[$CurrentSquad, target], soldiers]);
      
      for(%i=0;%i<%count;%i++)
      {
         %soldier = getWord($EnemySquad[$PlayerSquad[$CurrentSquad, target], soldiers], %i);               
         %soldier.SetBlending(true, ONE, ONE_MINUS_SRC_ALPHA);            
         %soldier.SetBlendColor(166, 0, 0, 255);
      }
   }   
   
   %soldier = getWord($PlayerSquad[$CurrentSquad, soldiers], 0);
   
   if(%soldier.dest !$= "")
   {
      greenflag.visible = true;
      greenflag.SetPosition(%soldier.dest);      
   }
   
   UpdatePeopleBattleWindow();
   
   echo("SELECT INFANTRY CLICK");   
   alxPlay(click);
}

function PreEndInfantryCombat(%winner)
{
   echo("BEGIN PRE END INFANTRY BATTLE");
   
   switch$ (%winner)
   {
      case "player":
         $combat = "";
         $peoplebattle = "";
         PutAmmoBack();
         DestroyInfantrySquads();
         Promotion();
         PromoteSergeant();   
         alxPlay(EndInfantryBattle);
         schedule(3000, 0, "EndInfantryBattle", true);
      case "enemy":      
         %soldiers = GetTotalCombatPeople();
         
         if(%soldiers > 0)
         {
            $combat = "";
            $peoplebattle = "";
            PutAmmoBack();
            DestroyInfantrySquads();
            BackToWorldStart();
            DecreaseMorale(3);
            LoseSuppliesFromInfantryDefeat();
         }
         else         
         {
            $combat = "";
            $peoplebattle = "";
            Canvas.PushDialog(EndGamemenu);         
         }
   }
   
   echo("END PRE END INFANTRY BATTLE");   
}

// if salvage is true it will allow the player to get guns and ammo

function EndInfantryBattle(%salvage)
{
   echo("BEGIN END INFANTRY BATTLE");
   
   BackToWorldStart();
        
   if($citycapturename !$= "")
      ShowCityBattleReport();
   else
      GetSuppliesAfterCityCombat();   
   
   echo("END INFANTRY BATTLE");      
}

function EndInfantryBattleFromRetreat()
{
   PutAmmoBack();
   DestroyInfantrySquads();
   $combat = "";
   $peoplebattle = "";
   DecreaseMorale(2);
   BackToWorldStart();
   
   echo("END INFANTRY BATTLE FROM RETREAT");      
}

function CreateRifleFire(%soldier)
{
      %effect = new t2dParticleEffect() {
      scenegraph = sg;
   };
   
   %effect.loadEffect( "~/data/particles/gunfire.eff" );   

   if(%soldier.player $= 1)
      %effect.mount(%soldier, ".2 -1", 0, true, true, true, true);  
   else
      %effect.mount(%soldier, "-.2 1", 0, true, true, true, true);  
   
   %effect.PlayEffect();
   
   return %effect;
}

function CheckEndInfantryCombat()
{
   // see if the Player is dead
   
   if(getWordCount($PlayerSquad[1, soldiers]) > 0)
      %alive = true;

   if(getWordCount($PlayerSquad[2, soldiers]) > 0)
      %alive = true;

   if(getWordCount($PlayerSquad[3, soldiers]) > 0)
      %alive = true;

   if(getWordCount($PlayerSquad[4, soldiers]) > 0)
      %alive = true;

   if(getWordCount($PlayerSquad[5, soldiers]) > 0)
      %alive = true;

   if(getWordCount($PlayerSquad[6, soldiers]) > 0)
      %alive = true;

   if(getWordCount($PlayerSquad[7, soldiers]) > 0)
      %alive = true;
   
   if(%alive $= "")
   {
      PreEndInfantryCombat(Enemy);              
      return true;
   }
   
   %alive = "";
   
   // see if the enemy is dead
   
   if(getWordCount($EnemySquad[1, soldiers]) > 0)
      %alive = true;

   if(getWordCount($EnemySquad[2, soldiers]) > 0)
      %alive = true;

   if(getWordCount($EnemySquad[3, soldiers]) > 0)
      %alive = true;

   if(getWordCount($EnemySquad[4, soldiers]) > 0)
      %alive = true;

   if(getWordCount($EnemySquad[5, soldiers]) > 0)
      %alive = true;

   if(getWordCount($EnemySquad[6, soldiers]) > 0)
      %alive = true;
   
   if(%alive $= "")
   {
      echo("PRE END");
      PreEndInfantryCombat(player);              
      return true;
   }
}

// after a sucessful combat put all the soldiers back into the pool

function DestroyInfantrySquads()
{
   if(getWordCount($PlayerSquad[1, soldiers]) > 0)
   {
      %count = getWordCount($PlayerSquad[1, soldiers]);
      
      for(%i=0;%i<%count;%i++)
      {
         %soldier = getWord($PlayerSquad[1, soldiers], %i);

         PutSoldierBack(%soldier.class);         
      }      
   }

   if(getWordCount($PlayerSquad[2, soldiers]) > 0)
   {
      %count = getWordCount($PlayerSquad[2, soldiers]);
      
      for(%i=0;%i<%count;%i++)
      {
         %soldier = getWord($PlayerSquad[2, soldiers], %i);

         PutSoldierBack(%soldier.class);         
      }                  
   }

   if(getWordCount($PlayerSquad[3, soldiers]) > 0)
   {
      %count = getWordCount($PlayerSquad[3, soldiers]);
      
      for(%i=0;%i<%count;%i++)
      {
         %soldier = getWord($PlayerSquad[3, soldiers], %i);

         PutSoldierBack(%soldier.class);         
      }      
   }

   if(getWordCount($PlayerSquad[4, soldiers]) > 0)
   {
      %count = getWordCount($PlayerSquad[4, soldiers]);
      
      for(%i=0;%i<%count;%i++)
      {
         %soldier = getWord($PlayerSquad[4, soldiers], %i);

         PutSoldierBack(%soldier.class);         
      }      
   }

   if(getWordCount($PlayerSquad[5, soldiers]) > 0)
   {
      %count = getWordCount($PlayerSquad[5, soldiers]);
      
      for(%i=0;%i<%count;%i++)
      {
         %soldier = getWord($PlayerSquad[5, soldiers], %i);

         PutSoldierBack(%soldier.class);         
      }      
   }

   if(getWordCount($PlayerSquad[6, soldiers]) > 0)
   {
      %count = getWordCount($PlayerSquad[6, soldiers]);
      
      for(%i=0;%i<%count;%i++)
      {
         %soldier = getWord($PlayerSquad[6, soldiers], %i);

         PutSoldierBack(%soldier.class);         
      }      
   }

   if(getWordCount($PlayerSquad[7, soldiers]) > 0)
   {
      %count = getWordCount($PlayerSquad[7, soldiers]);
      
      for(%i=0;%i<%count;%i++)
      {
         %soldier = getWord($PlayerSquad[7, soldiers], %i);

         PutSoldierBack(%soldier.class);         
      }      
   }
}

function PutSoldierBack(%class)
{
   switch$ (%class)
   {
      case "refuges":
            $refuges++; 
      case "brigands":
            $brigands++;
      case "police":
            $Police++;
      case "militia":
            $Militia++;
      case "soldiers":
            $Soldiers++;
      case "mercenaries":
            $Mercenaries++;
   }
}

function PutAmmoBack()
{
   $ammo = 0;   
   $ammo = $PlayerSquad[1, ammo]+$PlayerSquad[2, ammo]+$PlayerSquad[3, ammo]+$PlayerSquad[4, ammo]+$PlayerSquad[5, ammo]+$PlayerSquad[6, ammo]+$PlayerSquad[7, ammo];   
}

function AddPlayerInfantryCrossbowIcons(%squad)
{
   %count = getWordCount($PlayerSquad[%squad, soldiers]);
   
   for(%i=0;%i<%count;%i++)
   {
      %id = getWord($PlayerSquad[%squad, soldiers], %i);
      
      if(isObject(%id.gun) $= true)
        %id.gun.SafeDelete();
      
      %icon =    new t2dStaticSprite() {
                     layer = 6; 
                     scenegraph = "sg";
                     imageMap = "crossbow";
                     size = "4 5";
                  };
      
      %icon.Mount(%id, ".1 -.4" , 0, true, true, true, true);            
   }
}

function AddEnemyInfantryCrossbowIcons(%squad)
{
   %count = getWordCount($EnemySquad[%squad, soldiers]);

   for(%i=0;%i<%count;%i++)
   {
      %id = getWord($EnemySquad[%squad, soldiers], %i);

      if(isObject(%id.gun) $= true)
        %id.gun.SafeDelete();

      %icon =    new t2dStaticSprite() {
                     layer = 6; 
                     scenegraph = "sg";
                     imageMap = "crossbow";
                     size = "4 5";
                  };
      
      %icon.SetRotation(180);
      %icon.Mount(%id, "0 .6", 0, true, true, true, true);            
   }
}

function LoseSuppliesFromInfantryDefeat()
{
   %supplies = GetCurrentSupplyCount();
   
   %factor = "." @ getRandom(10, 30);
   
   %num = %supplies * %factor;
   %num = mCeil(%num);
      
   while(%num > 0)
   {
      %rand = getRandom(1, 7); 
               
      switch$ (%rand)
      {
         case 1:
            if($food > 0)
            {
               DecreaseFood(1);
               %num--;
               %food++;
            }
         case 2:
            if($guns > 0)
            {                  
               DecreaseGuns(1);
               %num--;
               %guns++;            
            }
         case 3:
            if($ammo > 0)
            {
               DecreaseAmmo(1);
               %num--;
               %ammo++;
            }
         case 4:
            if($medicine > 0)
            {
               DecreaseMedicine(1);
               %num--;
               %medicine++;            
            }
         case 5:
            if($tires > 0)
            {
               DecreaseTires(1);
               %num--;
               %tires++;            
            }
         case 6:
            if($spareparts > 0)
            {
               DecreaseSpareParts(1);
               %num--;
               %spareparts++;          
            }
         case 7:
            if($fuel > 0)
            {
               DecreaseFuel(1);
               %num--;
               %fuel++;          
            }
      }      
   }
         
   InfoText.addText("Some of your supplies have been stolen!\n\n", true);      

   if(%food > 0)
      InfoText.addText("You have lost " @ %food @ " food.\n", true);                  
   if(%guns > 0)
      InfoText.addText("You have lost " @ %guns @ " guns.\n", true);                                       
   if(%ammo > 0)
      InfoText.addText("You have lost " @ %ammo @ " ammo.\n", true);                           
   if(%medicine > 0)
      InfoText.addText("You have lost " @ %medicine @ " medicine.\n", true);                                       
   if(%tires > 0)
      InfoText.addText("You have lost " @ %tires @ " tires.\n", true);                                       
   if(%spareparts > 0)
      InfoText.addText("You have lost " @ %spareparts @ " spareparts.\n", true);                                     
   if(%fuel > 0)          
      InfoText.addText("You have lost " @ %fuel @ " fuel.\n", true);       
      
   Infowindow.Visible = true;
   InfoYesbutton.Visible = false;
   InfoNobutton.Visible = false;
   Infocontinuebutton.Visible = true;
   Infocontinuebutton.command = "infowindow.visible = false;";
}

function TurnOnInfantryCursor()
{
   canvas.CursorOn();   
}