// only 35 men are allowed on the battlefield at the same time

function BuildPlayerSoldiers()
{
   echo("BUILD PLAYER SOLDIERS");
      
   %count = GetTotalCombatPeople();
   
   if(%count > 35)
      %count = 35;
   
   for(%i=0;%i<%count;%i++)      
      AssignPlayerSquads();      
   
   echo("DONE ASSIGNING PLAYER SQUADS");
   
   if($PlayerSquad[1, soldiers] !$= "")
      PlacePlayerSoldiers(1);
   if($PlayerSquad[2, soldiers] !$= "")
      PlacePlayerSoldiers(2);
   if($PlayerSquad[3, soldiers] !$= "")
      PlacePlayerSoldiers(3);
   if($PlayerSquad[4, soldiers] !$= "")
      PlacePlayerSoldiers(4);
   if($PlayerSquad[5, soldiers] !$= "")
      PlacePlayerSoldiers(5);
   if($PlayerSquad[6, soldiers] !$= "")
      PlacePlayerSoldiers(6);
   if($PlayerSquad[7, soldiers] !$= "")
      PlacePlayerSoldiers(7);
      
   echo("DONE PLACING PLAYER SOLDIERS");
}

// this will take up to 35 soldiers and place them in squads

function AssignPlayerSquads()
{
   %id =    new t2dStaticSprite() {
      
            canSaveDynamicFields = "1";
            imageMap = "player_standing";
            scenegraph = "sg";
            size = "14 14";
            layer = 2;
            player = 1; // for gunfire  
            class = "PlayerInfantry";
         };

   %bolt =    new t2dStaticSprite() {
      
            canSaveDynamicFields = "1";
            imageMap = "bolt";
            scenegraph = "sg";
            size = "2 5";
            layer = 3;
         };
   
   %id.gun = %bolt;

   %bolt.Mount(%id, ".1 -.5", 0, true, true, true, true);
      
   // pull the soldier out at random
   
   while(%match $= "")
   {   
      %rand = getRandom(1, 6);
      
      switch$ (%rand)
      {
         case 1:
            if($refuges > 0)
            {
               $refuges--; 
               %id.class = "refuges";
               break;
            }
         case 2:
            if($Brigands > 0)
            {
               $brigands--;
               %id.class = "brigands";
               break;
            }
         case 3:
            if($police > 0)
            {
               %id.class = "police";
               $Police--;
               break;
            }
         case 4:
            if($militia > 0)
            {
               %id.class = "militia";
               $Militia--;
               break;
            }
         case 5:
            if($Soldiers > 0)
            {
               %id.class = "soldiers";
               $Soldiers--;
               break;
            }
         case 6:
            if($Mercenaries > 0)
            {
               %id.class = "mercenaries";
               $Mercenaries--;
               break;
            }
      }
   }
   
   // now assign the soldier to an empty squad
   
   if(getWordCount($PlayerSquad[1, soldiers]) < 5)
   {
      if($PlayerSquad[1, soldiers] $= "")
         $PlayerSquad[1, soldiers] = %id;
      else
         $PlayerSquad[1, soldiers] = $PlayerSquad[1, soldiers] SPC %id;      
         
      // assign the default position
      
      $PlayerSquad[1, position] = "Standing";
      $PlayerSquad[1, defensemodifier] = -1;
      
      %id.squad = 1;
        
      return;
   }
   
   if(getWordCount($PlayerSquad[2, soldiers]) < 5)
   {
      if($PlayerSquad[2, soldiers] $= "")
         $PlayerSquad[2, soldiers] = %id;
      else
         $PlayerSquad[2, soldiers] = $PlayerSquad[2, soldiers] SPC %id;      

      $PlayerSquad[2, position] = "Standing";
      $PlayerSquad[2, defensemodifier] = -1;

      %id.squad = 2;
         
      return;
   }

   if(getWordCount($PlayerSquad[3, soldiers]) < 5)
   {
      if($PlayerSquad[3, soldiers] $= "")
         $PlayerSquad[3, soldiers] = %id;
      else
         $PlayerSquad[3, soldiers] = $PlayerSquad[3, soldiers] SPC %id;      

      $PlayerSquad[3, position] = "Standing";
      $PlayerSquad[3, defensemodifier] = -1;

      %id.squad = 3;
         
      return;
   }

   if(getWordCount($PlayerSquad[4, soldiers]) < 5)
   {
      if($PlayerSquad[4, soldiers] $= "")
         $PlayerSquad[4, soldiers] = %id;
      else
         $PlayerSquad[4, soldiers] = $PlayerSquad[4, soldiers] SPC %id;      

      $PlayerSquad[4, position] = "Standing";
      $PlayerSquad[4, defensemodifier] = -1;

      %id.squad = 4;
         
      return;
   }

   if(getWordCount($PlayerSquad[5, soldiers]) < 5)
   {
      if($PlayerSquad[5, soldiers] $= "")
         $PlayerSquad[5, soldiers] = %id;
      else
         $PlayerSquad[5, soldiers] = $PlayerSquad[5, soldiers] SPC %id;      

      $PlayerSquad[5, position] = "Standing";
      $PlayerSquad[5, defensemodifier] = -1;
         
      %id.squad = 5;

      return;
   }

   if(getWordCount($PlayerSquad[6, soldiers]) < 5)
   {
      if($PlayerSquad[6, soldiers] $= "")
         $PlayerSquad[6, soldiers] = %id;
      else
         $PlayerSquad[6, soldiers] = $PlayerSquad[6, soldiers] SPC %id;      

      $PlayerSquad[6, position] = "Standing";
      $PlayerSquad[6, defensemodifier] = -1;

      %id.squad = 6;
         
      return;
   }

   if(getWordCount($PlayerSquad[7, soldiers]) < 5)
   {
      if($PlayerSquad[7, soldiers] $= "")
         $PlayerSquad[7, soldiers] = %id;
      else
         $PlayerSquad[7, soldiers] = $PlayerSquad[7, soldiers] SPC %id;      

      $PlayerSquad[7, position] = "Standing";
      $PlayerSquad[7, defensemodifier] = -1;

      %id.squad = 7;      
   }
}

function PlacePlayerSoldiers(%squad)
{
   for(%j=1;%j<=7;%j++)
   {
      %spawn = "p" @ %j;
      
      if(%spawn.taken $= "")         
      {
         %spawn.taken = true;
         %x = getWord(%spawn.GetPosition(), 0);
         %y = getWord(%spawn.GetPosition(), 1);
         
         %x = %x-20;
         
         for(%i=0;%i<=4;%i++)
         {
            switch$ (%squad)
            {
               case 1:
                  %soldier = getWord($PlayerSquad[1, soldiers], %i);
               case 2:
                  %soldier = getWord($PlayerSquad[2, soldiers], %i);
               case 3:
                  %soldier = getWord($PlayerSquad[3, soldiers], %i);
               case 4:
                  %soldier = getWord($PlayerSquad[4, soldiers], %i);
               case 5:
                  %soldier = getWord($PlayerSquad[5, soldiers], %i);
               case 6:
                  %soldier = getWord($PlayerSquad[6, soldiers], %i);
               case 7:
                  %soldier = getWord($PlayerSquad[7, soldiers], %i);
            }
                           
            if(%soldier !$= "")
            {
               %num = getRandom(1, 2);
               
               if(%num == 1)
                  %newy = %y+getRandom(0, 2);
               else
                  %newy = %y+getRandom(0, -2);
               
//               %soldier.SetPosition(%x, %newy);
               %soldier.SetPosition(getRandom(-100, 100), 120);

//               %x = %x+10;               
//               %layer = "infantry" @ $InfantryMap;      
//               %tile = %layer.PickTile(%soldier.GetPosition());
//               %layer.SetTileCustomData(getWord(%tile, 0) SPC getWord(%tile, 1), "block");
            }

               $CurrentSquad = %squad;
            
               MovePlayerInfantry(%x SPC %y);
         }
         
         break;  
      }
   }      
}

// if the player has 70 ammo or less divy it up in small numbers

function AssignPlayerAmmo()
{
   if($ammo <= 100)
      %amount = 10;   
   if($ammo > 100 && $ammo < 1400)
      %amount = 100;
   if($ammo >= 1400)
      %amount = 200;
      
   // start out on squad 1

   %squad = 1;
   
   // find out how many squads are going on the battlefield
   
   if($PlayerSquad[1, soldiers] !$= "")
      %maxsquad++;
   if($PlayerSquad[2, soldiers] !$= "")
      %maxsquad++;
   if($PlayerSquad[3, soldiers] !$= "")
      %maxsquad++;
   if($PlayerSquad[4, soldiers] !$= "")
      %maxsquad++;
   if($PlayerSquad[5, soldiers] !$= "")
      %maxsquad++;
   if($PlayerSquad[6, soldiers] !$= "")
      %maxsquad++;
   if($PlayerSquad[7, soldiers] !$= "")
      %maxsquad++;
   
   while($ammo > 0)
   {
      switch$(%squad)
      {
         case 1:
            if($ammo >= %amount)
            {
               $PlayerSquad[1, ammo] = $PlayerSquad[1, ammo]+%amount;            
               DecreaseAmmo(%amount);
            }
            else
            {
               $PlayerSquad[1, ammo] = $PlayerSquad[1, ammo]+$ammo;            
               $ammo = 0;                  
            }
         case 2:
            if($ammo >= %amount)
            {
               $PlayerSquad[2, ammo] = $PlayerSquad[2, ammo]+%amount;            
               DecreaseAmmo(%amount);
            }
            else
            {
               $PlayerSquad[2, ammo] = $PlayerSquad[2, ammo]+$ammo;            
               $ammo = 0;                  
            }
         case 3:
            if($ammo >= %amount)
            {
               $PlayerSquad[3, ammo] = $PlayerSquad[3, ammo]+%amount;            
               DecreaseAmmo(%amount);
            }
            else
            {
               $PlayerSquad[3, ammo] = $PlayerSquad[3, ammo]+$ammo;            
               $ammo = 0;                  
            }
         case 4:
            if($ammo >= %amount)
            {
               $PlayerSquad[4, ammo] = $PlayerSquad[4, ammo]+%amount;            
               DecreaseAmmo(%amount);
            }
            else
            {
               $PlayerSquad[4, ammo] = $PlayerSquad[4, ammo]+$ammo;            
               $ammo = 0;                  
            }
         case 5:
            if($ammo >= %amount)
            {
               $PlayerSquad[5, ammo] = $PlayerSquad[5, ammo]+%amount;            
               DecreaseAmmo(%amount);
            }
            else
            {
               $PlayerSquad[5, ammo] = $PlayerSquad[5, ammo]+$ammo;            
               $ammo = 0;                  
            }
         case 6:
            if($ammo >= %amount)
            {
               $PlayerSquad[6, ammo] = $PlayerSquad[6, ammo]+%amount;            
               DecreaseAmmo(%amount);
            }
            else
            {
               $PlayerSquad[6, ammo] = $PlayerSquad[6, ammo]+$ammo;            
               $ammo = 0;                  
            }
         case 7:            
            if($ammo >= %amount)
            {
               $PlayerSquad[7, ammo] = $PlayerSquad[7, ammo]+%amount;            
               DecreaseAmmo(%amount);
            }
            else
            {
               $PlayerSquad[7, ammo] = $PlayerSquad[7, ammo]+$ammo;            
               $ammo = 0;                  
            }
      }         
      
      %squad++;
      
      if(%squad > %maxsquad )
         %squad = 1;         
   }
}

// returns a value only

function GetPlayerCoverBonus(%squad)
{
   %count = getWordCount($PlayerSquad[%squad, soldiers]); 
   
   if(%count == 0)
      return;
      
   %cover = 0;
   
   switch$(%count)
   { 
      case 1:
         %soldier = getWord($PlayerSquad[%squad, soldiers], 0);    
      case 2:
         %soldier = getWord($PlayerSquad[%squad, soldiers], 1);          
      case 3:
         %soldier = getWord($PlayerSquad[%squad, soldiers], 1);          
      case 4:
         %soldier = getWord($PlayerSquad[%squad, soldiers], 1);          
      case 5:   
         %soldier = getWord($PlayerSquad[%squad, soldiers], 2);    
   }
   
   %x = getWord(%soldier.GetPosition(), 0);
   %y = getWord(%soldier.GetPosition(), 1);
   
   %list = sg.pickrect(%x-15 SPC %y-15, %x+15 SPC %y+15);
   
   %count = getWordCount(%list);
   
   for(%i=0;%i<%count;%i++)
   {
      %obj = getWord(%list, %i);
      
      if(%obj.cover $= true)
      {
         %cover = true;            
         break;
      }
   }
   
   if(%cover $= true)
      return 1;
   else
      return 0;   
}

// change the squad to either standing, kneeling or laying down

function InitChangePlayerSquadPosition()
{
   if($pause $= true)
   {
      alxPlay(buzzer);
      return;
   }
   
   if($PlayerSquad[$CurrentSquad, moving] $= true)
   {
      alxPlay(buzzer);
      return;
   }

   if($PlayerSquad[$CurrentSquad, ChangingPosition] $= true)
   {
      alxPlay(buzzer);
      return;
   }
   
   switch$ ($PlayerSquad[$CurrentSquad, position])
   {
      case "Standing":
         schedule(1000, 0, "CountDownPosition", $CurrentSquad, kneeling);
      case "Kneeling":
         schedule(1000, 0, "CountDownPosition", $CurrentSquad, prone);
      case "Prone":
         schedule(1000, 0, "CountDownPosition", $CurrentSquad, standing);
   }   

   $PlayerSquad[$CurrentSquad, timer] = 3;   
   $PlayerSquad[$CurrentSquad, ChangingPosition] = true;

   UpdatePeopleBattleWindow();
}

// this will allow the button to be updated with how much time it takes to switch positions

function CountDownPosition(%squad, %position)
{
   %count = getWordCount($PlayerSquad[%squad, soldiers]);      
   
   if(%count == 0)
      return;
      
   $PlayerSquad[%squad, timer]--;
   
   if($PlayerSquad[%squad, timer] $= 0)
   {
      $PlayerSquad[%squad, timer] = "";      
      
      switch$ (%position)
      {
         case "Standing":
            ChangePlayerPositionStanding(%squad);
         case "Kneeling":
            ChangePlayerPositionKneeling(%squad);
         case "Prone":
            ChangePlayerPositionProne(%squad);
      }   
   }
   else
      schedule(1000, 0, "CountDownPosition", %Squad, %position);
      
      UpdatePeopleBattleWindow();
}

function ChangePlayerPositionStanding(%squad)
{
   $PlayerSquad[%squad, ChangingPosition] = "";
   
   %image = "player_standing";
   pb_position.status = "standing";
   $PlayerSquad[%squad, defensemodifier] = 0;
   $PlayerSquad[%squad, position] = "Standing";

   %count = getWordCount($PlayerSquad[%squad, soldiers]);      
      
   for(%i=0;%i<%count;%i++)
   {
      %soldier = getWord($PlayerSquad[%squad, soldiers], %i);
      
      %soldier.SetImageMap(%image);      
   }
   
   UpdatePeopleBattleWindow();
}

function ChangePlayerPositionKneeling(%squad)
{
   $PlayerSquad[%squad, ChangingPosition] = "";

   %image = "player_kneel";         
   pb_position.status = "kneeling";
   $PlayerSquad[%squad, defensemodifier] = 1;
   $PlayerSquad[%squad, position] = "Kneeling";

   %count = getWordCount($PlayerSquad[%squad, soldiers]);      
      
   for(%i=0;%i<%count;%i++)
   {
      %soldier = getWord($PlayerSquad[%squad, soldiers], %i);
      
      %soldier.SetImageMap(%image);      
   }
   
   UpdatePeopleBattleWindow();
}

function ChangePlayerPositionProne(%squad)
{
   $PlayerSquad[%squad, ChangingPosition] = "";
   
   %image = "player_prone";
   pb_position.status = "prone";
   $PlayerSquad[%squad, defensemodifier] = 2;
   $PlayerSquad[%squad, position] = "Prone";

   %count = getWordCount($PlayerSquad[%squad, soldiers]);      
      
   for(%i=0;%i<%count;%i++)
   {
      %soldier = getWord($PlayerSquad[%squad, soldiers], %i);
      
      %soldier.SetImageMap(%image);      
   }
   
   UpdatePeopleBattleWindow();
}

function ScanForSoldierSelection(%coords)
{
   %list = sg.PickPoint(%coords);
   
   %count = getWordCount(%list);
   
   for(%i=0;%i<%count;%i++)
   {
      %obj = getWord(%list, %i);
      
      if(%obj.enemy $= 1)
      {
         %enemy = true;
         break;
      }
      if(%obj.player $= 1)
      {
         %player = true;
         break;
      }
   }
   
   if(%enemy $= true)
   {
      canvas.SetCursor(TargetCursor);
      $TargetEnemySoldiers = true;
   }
   else
   {
      canvas.SetCursor(GameCursor);
      $TargetEnemySoldiers = "";
   }
   
   if(%player $= true)
      $TargetPlayerSoldiers = true;      
   else
      $TargetPlayerSoldiers = "";      
}

function MovePlayerInfantry(%coords)
{
   %layer = "infantry" @ $InfantryMap;
   %tile = %layer.PickTile(%coords);   
   %block = %layer.GetTileCustomData(%tile);
   
   if(%block !$= "")
   {
      alxPlay(buzzer);
      greenflag.visible = false;
      return;
   }
   
   // the game will crash if it tries to generate a path of the map
   
   %dist = VectorDist("0 0", %coords);
   
   if(%dist > 100)
   {
      alxPlay(buzzer);
      greenflag.visible = false;
      return;
   }
   
   
   greenflag.visible = true;   
   greenflag.SetPosition(%coords);
         
   if($PlayerSquad[$currentSquad, position] !$= "Standing")
   {
      alxPlay(buzzer);
      return;
   }

   %count = getWordCount($PlayerSquad[$currentSquad, soldiers]);
   
   $currentgrid = %layer;

   %soldier = getWord($PlayerSquad[$currentSquad, soldiers], 0);
   %soldier.dest = %coords;
      
   for(%i=1;%i<%count;%i++)
   {   
      %soldier = getWord($PlayerSquad[$currentSquad, soldiers], %i);
      %x = getWord(%tile, 0);
      %y = getWord(%tile, 1);
      
      for(%j=1;%j<=8;%j++)
      {
         %dtile = %x-1 SPC %y;
         
         if(%layer.GetTileCustomData(%dtile) $= "" && %north $= "")                  
         {
            %north = true;
            %soldier.dest = getTCenter(%layer, %x-1, %y);
            break;
         }

         %dtile = %x+1 SPC %y;
         
         if(%layer.GetTileCustomData(%dtile) $= "" && %south $= "")                  
         {
            %south = true;
            %soldier.dest = getTCenter(%layer, %x+1, %y);
            break;
         }
         
         %dtile = %x SPC %y+1;
         
         if(%layer.GetTileCustomData(%dtile) $= "" && %east $= "")                  
         {
            %east = true;
            %soldier.dest = getTCenter(%layer, %x, %y+1);
            break;
         }

         %dtile = %x SPC %y-1;
         
         if(%layer.GetTileCustomData(%dtile) $= "" && %west $= "")                  
         {
            %west = true;
            %soldier.dest = getTCenter(%layer, %x, %y-1);
            break;
         }

         %dtile = %x-1 SPC %y+1;
         
         if(%layer.GetTileCustomData(%dtile) $= "" && %northwest $= "")                  
         {
            %northwest = true;
            %soldier.dest = getTCenter(%layer, %x-1, %y+1);
            break;
         }

         %dtile = %x-1 SPC %y-1;
         
         if(%layer.GetTileCustomData(%dtile) $= "" && %northeast $= "")                  
         {
            %northeast = true;
            %soldier.dest = getTCenter(%layer, %x-1, %y-1);
            break;
         }

         %dtile = %x+1 SPC %y+1;
         
         if(%layer.GetTileCustomData(%dtile) $= "" && %southwest $= "")                  
         {
            %southwest = true;
            %soldier.dest = getTCenter(%layer, %x+1, %y+1);
            break;
         }

         %dtile = %x+1 SPC %y-1;
         
         if(%layer.GetTileCustomData(%dtile) $= "" && %southwest $= "")                  
         {
            %southwest = true;
            %soldier.dest = getTCenter(%layer, %x+1, %y-1);
            break;
         }         
      }
   }
   
   // if each soldier does not have a destination then return
   
   for(%i=0;%i<%count;%i++)
   {
      %soldier = getWord($PlayerSquad[$currentSquad, soldiers], %i);
      
      if(%soldier.dest $= "")
      {
         alxPlay(buzzer);
         return;         
      }
   }
   
   $PlayerSquad[$currentSquad, moving] = true;
   
   for(%i=0;%i<%count;%i++)
   {
      %soldier = getWord($PlayerSquad[$currentSquad, soldiers], %i);
      %soldier.SetPosition(%soldier.GetPosition());
      %soldier.path = FindInfantryPath(%soldier, %soldier.dest);
      %coords = getWord(%soldier.path, 0) SPC getWord(%soldier.path, 1);
      schedule(%time, 0, "MoveSoldier", %soldier, %coords);
      %soldier.path = removeWord(%soldier.path, 0);
      %soldier.path = removeWord(%soldier.path, 0);
      %angle = t2dAngleToPoint(%soldier.GetPosition(), %coords);
      %soldier.SetRotation(%angle);
      %soldier.nofire = true;
      %time = %time+100;
      %tile = %layer.PickTile(%soldier.GetPosition());
      %layer.SetTileCustomData(getWord(%tile, 0) SPC getWord(%tile, 1), "");
   }   
}

function MoveSoldier(%soldier, %path)
{
   %soldier.moveto(%path, 25, true, true, true);
}

function PlayerInfantry::OnPositionTarget(%this)
{
   %coords = getWord(%this.path, 0) SPC getWord(%this.path, 1);
   
   %count = getWordCount(%coords);
   
   if(%count == 2)   
   {
      %angle = t2dAngleToPoint(%this.GetPosition(), %coords);
      %this.SetRotation(%angle);
      %this.moveto(%coords, 25, true, true, true);
   }
   else
   {
      // make sure this soldier faces the closest enemy
      %lowestdist = 1000;
      
      for(%i=1;%i<=4;%i++)
      {
         %count = getWordCount($EnemySquad[%i, soldiers]);
         
         if(%count > 0)
         {
            %soldier = getWord($EnemySquad[%i, soldiers], 0);
            
            %dist = VectorDist(%soldier.GetPosition(), %this.GetPosition());
            
            if(%dist < %lowestdist)
            {
               %position = %soldier.GetPosition();
               %lowestdist = %dist;   
            }
         }
      }
      
      %layer = "infantry" @ $InfantryMap;      
      %tile = %layer.PickTile(%this.GetPosition());
      %layer.SetTileCustomData(getWord(%tile, 0) SPC getWord(%tile, 1), "block");
      schedule(2000, 0, "ResetPlayerMoveFlag", %this.squad);     
      %angle = t2dAngleToPoint(%position, %this.GetPosition());
      %angle = %angle+180;
      %this.SetRotation(%angle);      
      %this.nofire = "";
      %this.dest = "";
      greenflag.visible = false;
   }
   
   %this.path = removeWord(%this.path, 0);
   %this.path = removeWord(%this.path, 0);
}

function ResetPlayerMoveFlag(%squad)
{
   $PlayerSquad[%squad, moving] = "";   
}

function InfantryRetreat()
{
   if($PlayerSquad[retreatcounter] !$= "")
      return;
      
   %count = 0;
   
   // count up all the enemy men currently on the battlefield
   
      %count = getWordCount($EnemySquad[1, soldiers]);
      %count = %count + getWordCount($EnemySquad[2, soldiers]);
      %count = %count + getWordCount($EnemySquad[3, soldiers]);
      %count = %count + getWordCount($EnemySquad[4, soldiers]);
      %count = %count + getWordCount($EnemySquad[5, soldiers]);
      %count = %count + getWordCount($EnemySquad[6, soldiers]);
   
   $PlayerSquad[retreatcounter] = %count;
   
   InfantryRetreatButton.setText("Retreat " @ $PlayerSquad[retreatcounter]);
   
   schedule(1000, 0, "UpdateRetreat");
}

function UpdateRetreat()
{
   // if the battle ends before they retreat
   
   if($peoplebattle $= "")
      return;
   
   $PlayerSquad[retreatcounter] = $PlayerSquad[retreatcounter]--;   
      
   InfantryRetreatButton.setText("  Retreat " @ $PlayerSquad[retreatcounter]);
   
   if($PlayerSquad[retreatcounter] == 0)
      EndInfantryBattleFromRetreat();
   else
      schedule(1000, 0, "UpdateRetreat");
}