//TownHall+Barrack Script written by ThundEEr[HU]
//Statistic script written by sado
//lowstart script by Ben modified by sado -3rd kind of start added by ThundEEr. - School>Inn+quarry>Wcutter
//TH image from the The Land of mercenaries script made by Andreus.
//
//
//
//
//
//The Townhall units are avaiable from the barrack if the rebuild/repair button enabled on it and if the player has a TownHall.
//The Trained TH units will walk out at TH.
//REbel- train lancecarrier
//Rouge train bowman
//Vagabond-train a scout 
//Warrior-train a militie- 1ironarmor+2swords
//barbs-train an axefighter-1leatherJAcket+2swords -something different for testing
//Of course the costs are cheper than the original unit's.
//Have to disable the trades of LeatherJacket,Woodenshied and AXE in the map editor.
//Modified. The second barrack disable the trades with the wares.
//Have Fun!

{-
================== README =================
==== Sadistic Statistics script by sado ===

Customizable features:
1. MAP_TYPE - 0 eco, 1 fighting/special
This feature disables some stuff that doesn't make sense on fight maps, for now it's only barracks overlay display. Feel free
 to enable on a map like The Raven's Field
2. BUILD_ORDER - 0 default, 1 koczis, 2 To
Building order. 
Default - School and Inn unlocked, after building School, unlocked Quarry and Woodcutter
koczis (oldschool style, as on Golden Cliffs) - School -> Inn -> Quarry -> Woodcutter
To (as on most maps of To) - all four buildings unlocked on start: School, Inn, Quarry, Woodcutter.
If your map needs something more detailed (like, you want some of the locs to have some extra unlocked buildings), you should be 
 able to unlock them in the editor if you're using Default or To orders. Koczis order might need unlocking in the script. Contact
 me if you need help with that, for me it's a 5 minute job.
3. TOWER_LIMIT (not done yet)
(0 for no limit)
4. STATS_FOR_ALL: when set to 1, every player can see kill statistics of both allies and enemies. When set to 0, player can see only the stats of his teammates.
5. Colors for the overlay can be customized. You create a color in a similar way to how you do that in ingame colored text:
 bgr (Blue, Green, Red) in hex system. An easy way is to use one of the HTML color generators (so you get a color like #45feaa) and switch 
 over two first and two last characters (so it becomes aafe45).

Non-customizable features:
Statistics for players about their teammates. Spectators will see statistics from the point of view of the spectated player.
1. Number of weapons in the barracks
2. Units produced, deaths, kills, "killpoints" (you get more points for killing knights than militia etc.)

TODO
Statistics export to file - if it's even possible
winning conditions
tower limit
HouseCanReachResources - beacons showing where the resources have depleted?
-}




Const //value for the added items to the barracks. these vaues only for the comfortabe train mass units. if there are huge values then 
//recommended to block trade leatherjacket, woodenshield and axe trades in the market!-DONE in the dynamic script!
//WS,LJ,AX recommend to be equal and be larger than 4-5. -Higer value makes comfortable training! Very high values can create trafficjams in front of the barracks.

WS= 20; // wares 16- woodenshield
LJ= 20; // wares 18- leather jacket
AX= 20; // wares 20- axe // THIS IS USED in THE OVERLAY TEXT!
MAP_TYPE = 0;
BUILD_ORDER = 1;
TOWER_LIMIT = 0; //doesn't work yet
STATS_FOR_ALL = 0;
INTERFACE_COLOR = 'aaaaaa';
IRON_COLOR = 'ffffb3';
LEATHER_COLOR = '3377ff';
HORSE_COLOR = '003366';
STAT_COLOR = 'ff6600';
RAD= 7;   //Townhall unit or group order radius


var BarracksList, Equipped, Lost, Defeated, DefeatedPoints: array [0..7] of Integer;
var BarrackCounter, Store, THCounter, THx, THy: array [0..7] of Integer;
var BuildOrderH: Integer;
var BaC: array [0..7] of Integer; //Barrack counter for the market trading blocking


procedure UpdateOverlay(Gametime, Player: Integer);
var Time,P,B,Sec,Recruits,M: Integer;
var WareColor: string;
begin
	Time := (States.PeaceTime - Gametime)/10;
	Actions.OverlayTextSet(Player,'[$'+INTERFACE_COLOR+']Time: ');
	if (States.PeaceTime > 0) and (States.PeaceTime > Gametime) then
	begin
		Actions.OverlayTextAppend(Player, IntToStr(Time /60) +':');
		Sec := Time mod 60;
		if (Sec < 10) then Actions.OverlayTextAppend(Player, '0'+IntToStr(Sec))
		else Actions.OverlayTextAppend(Player, IntToStr(Sec));
	end
	else
	begin
		Actions.OverlayTextAppend(Player, IntToStr(Gametime /600) +':');
		Sec := ((Gametime)/10) mod 60;
		if (Sec < 10) then Actions.OverlayTextAppend(Player, '0'+IntToStr(Sec))
		else Actions.OverlayTextAppend(Player, IntToStr(Sec));
	end;
	if ((MAP_TYPE=0) and (States.PeaceTime + 600 > Gametime)) or ((MAP_TYPE=0) and (States.PeaceTime = 0)) then
	begin
		Actions.OverlayTextAppend(Player,'|');
		for B := 16 to 25 do
			begin
				if (B mod 2) = 0 then
					WareColor := LEATHER_COLOR
				else
					WareColor := IRON_COLOR;
				if (B = 21) then Actions.OverlayTextAppend(Player,'|');
				Actions.OverlayTextAppend(Player,'[$'+WareColor+']'+ States.WareTypeName(B) + ', ');
			end;
		Actions.OverlayTextAppend(Player,'[$'+HORSE_COLOR+']'+ States.WareTypeName(26) + ', ');
		Actions.OverlayTextAppend(Player,'[$'+HORSE_COLOR+']'+ States.UnitTypeName(13) + ' ');
		for P := 0 to States.LocationCount-1 do
		begin
			if States.PlayerEnabled(P) and States.PlayerEnabled(Player) then
				begin
					if States.PlayerAllianceCheck(Player, P) or (Player = P) then
					begin
						if (BarracksList[P] = -1) then
						begin
							Actions.OverlayTextAppend(Player,'|[$' + States.PlayerColorText(P) + ']' + States.PlayerName(P) + ' [$'+INTERFACE_COLOR+']has no barracks yet');
						end
						else
						begin
							Actions.OverlayTextAppend(Player,'|[$' + States.PlayerColorText(P) + ']' + States.PlayerName(P) + ': ');
							for B := 16 to 25 do
								begin
									if (B= 16) or (B= 18) or (B= 20) then begin
										M:= -AX;
										WareColor := LEATHER_COLOR
										Actions.OverlayTextAppend(Player,'[$'+WareColor+']'+IntToStr(States.HouseResourceAmount(BarracksList[P],B)+M) + ' ');
									end else 
									if (B= 22) or (B= 24) then begin
										WareColor := LEATHER_COLOR
										M:= 0;
										Actions.OverlayTextAppend(Player,'[$'+WareColor+']'+IntToStr(States.HouseResourceAmount(BarracksList[P],B)+M) + ' ');
									end else
									if (B=17) or (B= 19) or (B= 21) or (B= 23) or (B= 25) then begin
										M:= 0;
										WareColor := IRON_COLOR;
										Actions.OverlayTextAppend(Player,'[$'+WareColor+']'+IntToStr(States.HouseResourceAmount(BarracksList[P],B)+M) + ' ');
									end; 
								end;
							Actions.OverlayTextAppend(Player,'[$'+HORSE_COLOR+']'+IntToStr(States.HouseResourceAmount(BarracksList[P],26)) + ' ');
							Recruits := States.StatUnitTypeCount(P, 13) - States.StatHouseTypeCount(P,17);
							Actions.OverlayTextAppend(Player,'[$'+HORSE_COLOR+']'+ IntToStr(Recruits) + ' ');
						end;
					end;
				end;
		end;
	end;
	if ((MAP_TYPE=0) and (States.PeaceTime < Gametime)) or (States.PeaceTime = 0) then
	begin
		Actions.OverlayTextAppend(Player,'||[$'+INTERFACE_COLOR+']Kill statistics: ' );
		for P := 0 to States.LocationCount-1 do
		begin
			if States.PlayerEnabled(P) and States.PlayerEnabled(Player) then
				begin
					if States.PlayerAllianceCheck(Player, P) or (Player = P) or (STATS_FOR_ALL=1) then
					begin
						Actions.OverlayTextAppend(Player,'|[$' + States.PlayerColorText(P) + ']' + States.PlayerName(P) +': [$'+STAT_COLOR+']'+ IntToStr(Equipped[P]) + '[$'+INTERFACE_COLOR+'] trained, [$'+STAT_COLOR+']' + IntToStr(Lost[P]) + '[$'+INTERFACE_COLOR+'] deaths, [$'+STAT_COLOR+']' + IntToStr(Defeated[P]) + '[$'+INTERFACE_COLOR+'] kills, [$'+STAT_COLOR+']' + IntToStr(DefeatedPoints[P]) + '[$'+INTERFACE_COLOR+'] killpoints ');
					end;
				end;
		end;
	end;
end;

function GetUnitPoints(aUnitType: Integer): Integer;
var Points: Integer;
begin
	case aUnitType of			// Thundy -point system
		14,24,25: Points := 1; 	//militia,rebel,rogue
		19,27: Points := 2; 	//lance,vaga
		15: Points := 3; 		//axe
		20,21: Points := 3; 	//pike,scout
		16: Points := 4;		//sword
		17: Points := 2;		//bow
		18: Points := 3;		//xbow
		22: Points := 5;		//knight 
		23,26: Points := 3;		//barb, warr
		
		//Original point system by sado
		//14,24,25: Points := 1; 	//militia,rebel,rogue
		//19,27: Points := 1; 	//lance,vaga
		//15: Points := 2; 		//axe
		//20,21: Points := 2; 	//pike,scout
		//16: Points := 3;		//sword
		//17: Points := 1;		//bow
		//18: Points := 2;		//xbow
		//22,23,26: Points := 4;	//knight, barb, warr	
		
		
		
	else Points := 0;
	end;
	Result := Points;
	Exit;
end;

procedure OnUnitDied(aUnit, aKiller: Integer);
begin
	if (aKiller <> -1) then
	begin
		Inc(Lost[States.UnitOwner(aUnit)]);
		Inc(Defeated[aKiller]);
		DefeatedPoints[aKiller] := DefeatedPoints[aKiller] + GetUnitPoints(States.UnitType(aUnit));
	end;
end;




procedure OnMissionStart;			//Disable the fast start and some trades in the barrack.
									// TH builds up
var P: Integer;
var Houses: array of Integer;

begin
	BuildOrderH := BUILD_ORDER;
  for P := 0 to 7 do
    if States.PlayerEnabled(P) then
    begin
		case BuildOrderH of
		1: begin
			Actions.HouseAllow(P, 27, False);  //inn
			Actions.HouseAllow(P, 14, False);  //quarry
			Actions.HouseAllow(P, 9, False);  //cutter
			//DEBUG
			//Actions.HouseUnlock(P, 19);
			//Actions.HouseUnlock(P, 21);
			end;
		2: begin
				Actions.HouseUnlock(P, 27);
				Actions.HouseUnlock(P, 14);
				Actions.HouseUnlock(P, 9);
			end;
		end;
		BarracksList[P] := -1;
		BarrackCounter[P] := -1;
		Houses := States.PlayerGetAllHouses(P);
        Store[P] := Houses[0];
		THCounter[P] := 0 ;
		THx[P] := -1;
		THy[P] := -1;
   end;     
end;





//Buildng TH phisically placement. Only if barrack is avaiable.
procedure OnHousePlanPlaced(P, X, Y, T: Integer);
begin
  if T = 21 then
    if (States.HouseRepair(Store[P])) //then
	 and (THCounter[P] = 0) then
				//and (States.StatHouseTypeCount(P, 15) > 0) then
    begin
      Actions.PlanRemove(P, X, Y);
      if States.IsRoadAt(P, X, Y + 1) then
        Actions.PlanAddHouse(P, 18, X, Y);
      if not States.IsRoadAt(P, X, Y + 1) then
        Actions.PlanAddHouse(P, 18, X, Y - 1);
      
      Actions.HouseRepairEnable(Store[P], False);
	  inc(THCounter[P]);
    end;
end;

//remove placement and dec the counter
procedure OnHousePlanRemoved(P, X, Y, T: Integer);
begin
  if T = 18 then 
    dec(THCounter[P]);
end;




procedure OnWarriorEquipped (aUnitID: Integer ; aGroupID: Integer);  //happening when an warriror equipped
var aBarracks: Integer;
//aSecondDoor: Integer;		//was used for the second door to barrack
OW, TW, UT, UX, UY: Integer;			//used for TH owner and counter; OWner, ToWnhall; ClosetGroup ID, UnitType
//CG: Integer;

begin
//the follow things are need because some of these units has to be untrainable if there arent enough weapons in the barrack.
// Weapons need to activate buttons, more weapons need to be able to train units comfortable.
OW := States.UnitOwner(aUnitID);
TW := THCounter [OW];
//Milite 
if States.UnitType(aUnitID) = 14 then begin
			Inc(Equipped[States.UnitOwner(aUnitID)]);
					aBarracks := States.ClosestHouse(States.UnitOwner(aUnitID), States.UnitPositionX(aUnitID), States.UnitPositionY(aUnitID), 21);
				if (States.HouseResourceAmount(aBarracks, 20) < AX) and (States.HouseRepair(aBarracks) = false) then begin
					Dec(Equipped[States.UnitOwner(aUnitID)]);
					Actions.UnitKill(aUnitID, True);
					Actions.HouseAddWaresTo(aBarracks, 20, 1);
					Actions.HouseBarracksGiveRecruit(aBarracks);
				end;
				
				//deleted th bug fixation;
		
				if (States.HouseRepair(aBarracks) = true) and (States.StatHouseTypeCount(States.UnitOwner(aUnitID), 18) < 1) and (States.HouseResourceAmount(aBarracks, 20) < AX) then begin   //axf is not trainable because th 0
					Dec(Equipped[States.UnitOwner(aUnitID)]);
					Actions.UnitKill(aUnitID, True);
					Actions.HouseAddWaresTo(aBarracks, 20, 1);
					Actions.HouseBarracksGiveRecruit(aBarracks);
				end;
				
					
end;

//Bowman 17
if States.UnitType(aUnitID) = 17 then begin
			Inc(Equipped[States.UnitOwner(aUnitID)]);
		aBarracks := States.ClosestHouse(States.UnitOwner(aUnitID), States.UnitPositionX(aUnitID), States.UnitPositionY(aUnitID), 21);
				if (States.HouseResourceAmount(aBarracks, 18) < LJ) and (States.HouseRepair(aBarracks) = false) then begin
					Dec(Equipped[States.UnitOwner(aUnitID)]);
					Actions.UnitKill(aUnitID, True);
					Actions.HouseAddWaresTo(aBarracks, 24, 1);
					Actions.HouseAddWaresTo(aBarracks, 18, 1);
					Actions.HouseBarracksGiveRecruit(aBarracks);
				end;
				
				//deleted th bug fixation;
		
				if (States.HouseRepair(aBarracks) = true) and (States.StatHouseTypeCount(States.UnitOwner(aUnitID), 18) < 1) and (States.HouseResourceAmount(aBarracks, 18) < LJ)  then begin   //axf is not trainable because th 0
					Dec(Equipped[States.UnitOwner(aUnitID)]);
					Actions.UnitKill(aUnitID, True);
					Actions.HouseAddWaresTo(aBarracks, 24, 1);
					Actions.HouseAddWaresTo(aBarracks, 18, 1);
					Actions.HouseBarracksGiveRecruit(aBarracks);
				end;
				
					
end;

//Axefighter 15
if States.UnitType(aUnitID) = 15 then begin
			Inc(Equipped[States.UnitOwner(aUnitID)]);
		aBarracks := States.ClosestHouse(States.UnitOwner(aUnitID), States.UnitPositionX(aUnitID), States.UnitPositionY(aUnitID), 21);
				if (States.HouseRepair(aBarracks) = false) and ((States.HouseResourceAmount(aBarracks, 18) < LJ) or (States.HouseResourceAmount(aBarracks, 16) < WS) or (States.HouseResourceAmount(aBarracks, 20) < AX))then begin
				Dec(Equipped[States.UnitOwner(aUnitID)]);
				Actions.UnitKill(aUnitID, true);
				Actions.HouseAddWaresTo(aBarracks, 16, 1);
				Actions.HouseAddWaresTo(aBarracks, 18, 1);
				Actions.HouseAddWaresTo(aBarracks, 20, 1);
				Actions.HouseBarracksGiveRecruit(aBarracks);
				end;
				
				//deleted th bug fixation;
		
				if (States.HouseRepair(aBarracks) = true) and (States.StatHouseTypeCount(States.UnitOwner(aUnitID), 18) < 1) and ((States.HouseResourceAmount(aBarracks, 18) < LJ) or (States.HouseResourceAmount(aBarracks, 16) < WS) or (States.HouseResourceAmount(aBarracks, 20) < AX)) then begin   //axf is not trainable because th 0
					Dec(Equipped[States.UnitOwner(aUnitID)]);
					Actions.UnitKill(aUnitID, True);
					Actions.HouseAddWaresTo(aBarracks, 16, 1);
					Actions.HouseAddWaresTo(aBarracks, 18, 1);
					Actions.HouseAddWaresTo(aBarracks, 20, 1);
					Actions.HouseBarracksGiveRecruit(aBarracks);
				end;
				
				
end;

//Barb---If the axefigther trained when the repair button is enabled. The else need to definiate when there arent enoguh ware to train barbs. Cost is 1 LJ+ 2 SW
if States.UnitType(aUnitID) = 15 then begin
		aBarracks := States.ClosestHouse(States.UnitOwner(aUnitID), States.UnitPositionX(aUnitID), States.UnitPositionY(aUnitID), 21);
		OW := States.UnitOwner(aUnitID);
		
		//second door
			//if States.ConnectedByWalking(States.UnitPositionX(aUnitID), States.UnitPositionY(aUnitID), States.UnitPositionX(aUnitID), (States.UnitPositionY(aUnitID)-5) ) = true then
			//aSecondDoor := (States.UnitPositionY(aUnitID)-5);
			//if States.ConnectedByWalking(States.UnitPositionX(aUnitID), States.UnitPositionY(aUnitID), States.UnitPositionX(aUnitID), (States.UnitPositionY(aUnitID)-5) ) = false then
			//aSecondDoor := States.UnitPositionY(aUnitID);
		if (States.HouseRepair(aBarracks) = true) and (States.StatHouseTypeCount(States.UnitOwner(aUnitID), 18) > 0) then begin	
			if aBarracks > -1 then begin
					if (States.HouseResourceAmount(aBarracks, 18) >= LJ) and (States.HouseResourceAmount(aBarracks, 21) >= 2) then begin  //barb is trainable
					
					//setting the group ID
					//Closet group next to the TH and not more than 5-6tiles. then connect to this group
					UT:= States.ClosestUnit(States.UnitOwner(aUnitID), THx[States.UnitOwner(aUnitID)], THy[States.UnitOwner(aUnitID)], 23);
					UX:= States.UnitPositionX(UT);
					UY:= States.UnitPositionY(UT);
							if (THx[States.UnitOwner(aUnitID)] - RAD  < UX) and (UX < THx[States.UnitOwner(aUnitID)] + RAD) and (THy[States.UnitOwner(aUnitID)] - RAD  < UY) and (UY < THy[States.UnitOwner(aUnitID)] + RAD ) then begin
							aGroupID:= States.GroupAt(UX,UY);
							end;
					//adding the troops					
					Actions.GroupOrderLink(Actions.GiveGroup(States.UnitOwner(aUnitID), 23, THx[States.UnitOwner(aUnitID)], 1 + THy[States.UnitOwner(aUnitID)], States.UnitDirection(aUnitID),1,1), aGroupID);
					Actions.UnitKill(aUnitID, True);
					Actions.HouseAddWaresTo(aBarracks, 20, 1);
					Actions.HouseAddWaresTo(aBarracks, 16, 1);
					Actions.HouseTakeWaresFrom(aBarracks, 21, 2);
					end else begin
					
					if ((States.HouseResourceAmount(aBarracks, 18)  < LJ) or (States.HouseResourceAmount(aBarracks, 21) < 3)) and (States.HouseResourceAmount(aBarracks, 20) >= 0) and (States.HouseResourceAmount(aBarracks, 16) >= 0) then begin //barb is not trainable
					Dec(Equipped[States.UnitOwner(aUnitID)]);
					Actions.UnitKill(aUnitID, True);
					Actions.HouseAddWaresTo(aBarracks, 16, 1);
					Actions.HouseAddWaresTo(aBarracks, 18, 1);
					Actions.HouseAddWaresTo(aBarracks, 20, 1);
					Actions.HouseBarracksGiveRecruit(aBarracks);
					end;
					end;
			end;
		end;	
	end;
	
//Lance carrier19
if States.UnitType(aUnitID) = 19 then begin
		Inc(Equipped[States.UnitOwner(aUnitID)]);
		aBarracks := States.ClosestHouse(States.UnitOwner(aUnitID), States.UnitPositionX(aUnitID), States.UnitPositionY(aUnitID), 21);
				if (States.HouseResourceAmount(aBarracks, 18) < LJ) and (States.HouseRepair(aBarracks) = false) then begin
				Dec(Equipped[States.UnitOwner(aUnitID)]);
				Actions.UnitKill(aUnitID, True);
				Actions.HouseAddWaresTo(aBarracks, 22, 1);
				Actions.HouseAddWaresTo(aBarracks, 18, 1);
				Actions.HouseBarracksGiveRecruit(aBarracks);
				end;
				
				//deleted th bug fixation;
		
				if (States.HouseRepair(aBarracks) = true) and (States.StatHouseTypeCount(States.UnitOwner(aUnitID), 18) < 1) and (States.HouseResourceAmount(aBarracks, 18) < LJ)  then begin   //axf is not trainable because th 0
					Dec(Equipped[States.UnitOwner(aUnitID)]);
					Actions.UnitKill(aUnitID, True);
					Actions.HouseAddWaresTo(aBarracks, 22, 1);
					Actions.HouseAddWaresTo(aBarracks, 18, 1);
					Actions.HouseBarracksGiveRecruit(aBarracks);
				end;
				
end;



//Warrior
if States.UnitType(aUnitID) = 14 then begin
		aBarracks := States.ClosestHouse(States.UnitOwner(aUnitID), States.UnitPositionX(aUnitID), States.UnitPositionY(aUnitID), 21);
		OW := States.UnitOwner(aUnitID);
		
		//second door
		//if States.ConnectedByWalking(States.UnitPositionX(aUnitID), States.UnitPositionY(aUnitID), States.UnitPositionX(aUnitID), (States.UnitPositionY(aUnitID)-5) ) = true then
		//aSecondDoor := (States.UnitPositionY(aUnitID)-5);
		//if States.ConnectedByWalking(States.UnitPositionX(aUnitID), States.UnitPositionY(aUnitID), States.UnitPositionX(aUnitID), (States.UnitPositionY(aUnitID)-5) ) = false then
		//aSecondDoor := States.UnitPositionY(aUnitID);
		if (States.HouseRepair(aBarracks) = true) and (States.StatHouseTypeCount(States.UnitOwner(aUnitID), 18) > 0) then begin	
			if aBarracks > -1 then begin
					//setting the group ID
					//Closet group next to the TH and not more than 5-6tiles. then connect to this group
					UT:= States.ClosestUnit(States.UnitOwner(aUnitID), THx[States.UnitOwner(aUnitID)], THy[States.UnitOwner(aUnitID)], 26);
					UX:= States.UnitPositionX(UT);
					UY:= States.UnitPositionY(UT);
							if (THx[States.UnitOwner(aUnitID)] - RAD  < UX) and (UX < THx[States.UnitOwner(aUnitID)] + RAD) and (THy[States.UnitOwner(aUnitID)] - RAD  < UY) and (UY < THy[States.UnitOwner(aUnitID)] + RAD ) then begin
							aGroupID:= States.GroupAt(UX,UY);
							end;
			
			
					if (States.HouseResourceAmount(aBarracks, 19) >= 1) and (States.HouseResourceAmount(aBarracks, 21) >= 2) then begin
					Actions.GroupOrderLink(Actions.GiveGroup(States.UnitOwner(aUnitID), 26, THx[States.UnitOwner(aUnitID)], 1 + THy[States.UnitOwner(aUnitID)], States.UnitDirection(aUnitID),1,1), aGroupID);
					Actions.UnitKill(aUnitID, True);
					Actions.HouseAddWaresTo(aBarracks, 20, 1);
					Actions.HouseTakeWaresFrom(aBarracks, 21, 2);
					Actions.HouseTakeWaresFrom(aBarracks, 19, 1);
					end;
			end;
		end;	
	end;
	
//Warrior is not trainable, when not enough iron stuffs are there.
	if States.UnitType(aUnitID) = 14 then begin
		aBarracks := States.ClosestHouse(States.UnitOwner(aUnitID), States.UnitPositionX(aUnitID), States.UnitPositionY(aUnitID), 21);
		OW := States.UnitOwner(aUnitID);
		if (States.HouseRepair(aBarracks) = true) and (States.StatHouseTypeCount(States.UnitOwner(aUnitID), 18) > 0) then begin	
			if aBarracks > -1 then begin
					if ((States.HouseResourceAmount(aBarracks, 19)  < 2) or (States.HouseResourceAmount(aBarracks, 21) < 3)) then begin
					Dec(Equipped[States.UnitOwner(aUnitID)]);
					Actions.UnitKill(aUnitID, True);
					Actions.HouseAddWaresTo(aBarracks, 20, 1);
					Actions.HouseBarracksGiveRecruit(aBarracks);
				end;
			end;
		end;	
	end;

//Rebel
	if States.UnitType(aUnitID) = 19 then begin
		aBarracks := States.ClosestHouse(States.UnitOwner(aUnitID), States.UnitPositionX(aUnitID), States.UnitPositionY(aUnitID), 21);
		OW := States.UnitOwner(aUnitID);
		//second door
		//if States.ConnectedByWalking(States.UnitPositionX(aUnitID), States.UnitPositionY(aUnitID), States.UnitPositionX(aUnitID), (States.UnitPositionY(aUnitID)-5) ) = true then
		//aSecondDoor := (States.UnitPositionY(aUnitID)-5);
		//if States.ConnectedByWalking(States.UnitPositionX(aUnitID), States.UnitPositionY(aUnitID), States.UnitPositionX(aUnitID), (States.UnitPositionY(aUnitID)-5) ) = false then
		//aSecondDoor := States.UnitPositionY(aUnitID);
		if (States.HouseRepair(aBarracks) = true) and (States.StatHouseTypeCount(States.UnitOwner(aUnitID), 18) > 0) then begin	
			if aBarracks > -1 then begin
					//setting the group ID
					//Closet group next to the TH and not more than 5-6tiles. then connect to this group
					UT:= States.ClosestUnit(States.UnitOwner(aUnitID), THx[States.UnitOwner(aUnitID)], THy[States.UnitOwner(aUnitID)], 24);
					UX:= States.UnitPositionX(UT);
					UY:= States.UnitPositionY(UT);
							if (THx[States.UnitOwner(aUnitID)] - RAD  < UX) and (UX < THx[States.UnitOwner(aUnitID)] + RAD) and (THy[States.UnitOwner(aUnitID)] - RAD  < UY) and (UY < THy[States.UnitOwner(aUnitID)] + RAD ) then begin
							aGroupID:= States.GroupAt(UX,UY);
							end;
			
			
					if (States.HouseResourceAmount(aBarracks, 18) >= 0) then begin
					Actions.GroupOrderLink(Actions.GiveGroup(States.UnitOwner(aUnitID), 24, THx[States.UnitOwner(aUnitID)], 1 + THy[States.UnitOwner(aUnitID)], States.UnitDirection(aUnitID),1,1), aGroupID);
					Actions.HouseAddWaresTo(aBarracks, 18, 1);
				end;
				Actions.UnitKill(aUnitID, True);
			end;
		end;	
	end;
	
//Rouge
if States.UnitType(aUnitID) = 17 then begin
		aBarracks := States.ClosestHouse(States.UnitOwner(aUnitID), States.UnitPositionX(aUnitID), States.UnitPositionY(aUnitID), 21);
		OW := States.UnitOwner(aUnitID);
		//second door
		//if States.ConnectedByWalking(States.UnitPositionX(aUnitID), States.UnitPositionY(aUnitID), States.UnitPositionX(aUnitID), (States.UnitPositionY(aUnitID)-5) ) = true then
		//aSecondDoor := (States.UnitPositionY(aUnitID)-5);
		//if States.ConnectedByWalking(States.UnitPositionX(aUnitID), States.UnitPositionY(aUnitID), States.UnitPositionX(aUnitID), (States.UnitPositionY(aUnitID)-5) ) = false then
		//aSecondDoor := States.UnitPositionY(aUnitID);
		if (States.HouseRepair(aBarracks) = true) and (States.StatHouseTypeCount(States.UnitOwner(aUnitID), 18) > 0) then begin	
			if aBarracks > -1 then begin
					//setting the group ID
					//Closet group next to the TH and not more than 5-6tiles. then connect to this group
					UT:= States.ClosestUnit(States.UnitOwner(aUnitID), THx[States.UnitOwner(aUnitID)], THy[States.UnitOwner(aUnitID)], 25);
					UX:= States.UnitPositionX(UT);
					UY:= States.UnitPositionY(UT);
							if (THx[States.UnitOwner(aUnitID)] - RAD  < UX) and (UX < THx[States.UnitOwner(aUnitID)] + RAD) and (THy[States.UnitOwner(aUnitID)] - RAD  < UY) and (UY < THy[States.UnitOwner(aUnitID)] + RAD ) then begin
							aGroupID:= States.GroupAt(UX,UY);
							end;
			
					if (States.HouseResourceAmount(aBarracks, 18) >= 0) then begin
					Actions.GroupOrderLink(Actions.GiveGroup(States.UnitOwner(aUnitID), 25, THx[States.UnitOwner(aUnitID)], 1 + THy[States.UnitOwner(aUnitID)], States.UnitDirection(aUnitID),1,1), aGroupID);
					Actions.HouseAddWaresTo(aBarracks, 18, 1);
					end;
				Actions.UnitKill(aUnitID, True);
			end;
		end;	
	end;


//The follow units only for the trained unit counter, except the scout;
//SWordman
if States.UnitType(aUnitID) = 16 then begin
Inc(Equipped[States.UnitOwner(aUnitID)]);
end;

//Pike
if States.UnitType(aUnitID) = 20 then begin
Inc(Equipped[States.UnitOwner(aUnitID)]);
end;

//Xbow
if States.UnitType(aUnitID) = 18 then begin
Inc(Equipped[States.UnitOwner(aUnitID)]);
end;

//Knight
if States.UnitType(aUnitID) = 22 then begin
Inc(Equipped[States.UnitOwner(aUnitID)]);
end;
	
//Scout21
if States.UnitType(aUnitID) = 21 then begin    //21-scout
		Inc(Equipped[States.UnitOwner(aUnitID)]);
		
		aBarracks := States.ClosestHouse(States.UnitOwner(aUnitID), States.UnitPositionX(aUnitID), States.UnitPositionY(aUnitID), 21);
		OW := States.UnitOwner(aUnitID);
		//second door
		//if States.ConnectedByWalking(States.UnitPositionX(aUnitID), States.UnitPositionY(aUnitID), States.UnitPositionX(aUnitID), (States.UnitPositionY(aUnitID)-5) ) = true then
		//aSecondDoor := (States.UnitPositionY(aUnitID)-5);
		//if States.ConnectedByWalking(States.UnitPositionX(aUnitID), States.UnitPositionY(aUnitID), States.UnitPositionX(aUnitID), (States.UnitPositionY(aUnitID)-5) ) = false then
		//aSecondDoor := States.UnitPositionY(aUnitID);
		if(States.HouseRepair(aBarracks) = false) then begin
			if aBarracks > -1 then begin
				if ((States.HouseResourceAmount(aBarracks, 18) < LJ) or (States.HouseResourceAmount(aBarracks, 16) < WS) or (States.HouseResourceAmount(aBarracks, 20) < AX))  then begin
				Dec(Equipped[States.UnitOwner(aUnitID)]);
				Actions.UnitKill(aUnitID, True);
				Actions.HouseAddWaresTo(aBarracks, 16, 1);
				Actions.HouseAddWaresTo(aBarracks, 18, 1);
				Actions.HouseAddWaresTo(aBarracks, 20, 1);
				Actions.HouseAddWaresTo(aBarracks, 26, 1);
				Actions.HouseBarracksGiveRecruit(aBarracks);
				end;
			end;
		end else begin
		
		//deleted th bug fixation;
		
			if (States.HouseRepair(aBarracks) = true) and (States.StatHouseTypeCount(States.UnitOwner(aUnitID), 18) < 1) and ((States.HouseResourceAmount(aBarracks, 18) < LJ) or (States.HouseResourceAmount(aBarracks, 16) < WS) or (States.HouseResourceAmount(aBarracks, 20) < AX)) then begin   //axf is not trainable because th 0
					if aBarracks > -1 then begin
					Dec(Equipped[States.UnitOwner(aUnitID)]);
					Actions.UnitKill(aUnitID, True);
					Actions.HouseAddWaresTo(aBarracks, 16, 1);
					Actions.HouseAddWaresTo(aBarracks, 18, 1);
					Actions.HouseAddWaresTo(aBarracks, 20, 1);
					Actions.HouseAddWaresTo(aBarracks, 26, 1);
					Actions.HouseBarracksGiveRecruit(aBarracks);
					
					end;
				end else 										//until this
		
		if (States.HouseRepair(aBarracks) = true) and (States.StatHouseTypeCount(States.UnitOwner(aUnitID), 18) > 0) then begin	
			if aBarracks > -1 then begin
					//setting the group ID
					//Closet group next to the TH and not more than 5-6tiles. then connect to this group
					UT:= States.ClosestUnit(States.UnitOwner(aUnitID), THx[States.UnitOwner(aUnitID)], THy[States.UnitOwner(aUnitID)], 27);
					UX:= States.UnitPositionX(UT);
					UY:= States.UnitPositionY(UT);
							if (THx[States.UnitOwner(aUnitID)] - RAD  < UX) and (UX < THx[States.UnitOwner(aUnitID)] + RAD) and (THy[States.UnitOwner(aUnitID)] - RAD  < UY) and (UY < THy[States.UnitOwner(aUnitID)] + RAD ) then begin
							aGroupID:= States.GroupAt(UX,UY);
							end;
			
					if (States.HouseResourceAmount(aBarracks, 20) >= (AX)) and (States.HouseResourceAmount(aBarracks, 18) >= 0) and (States.HouseResourceAmount(aBarracks, 16) >= 0) then begin
					Actions.GroupOrderLink(Actions.GiveGroup(States.UnitOwner(aUnitID), 27, THx[States.UnitOwner(aUnitID)], 1 + THy[States.UnitOwner(aUnitID)], States.UnitDirection(aUnitID),1,1), aGroupID);
					Actions.HouseAddWaresTo(aBarracks, 18, 1);
					Actions.HouseAddWaresTo(aBarracks, 16, 1);
					Actions.UnitKill(aUnitID, True);
					end else begin
					if (States.HouseResourceAmount(aBarracks, 20) < (AX)) and (States.HouseResourceAmount(aBarracks, 18) >= 0) and (States.HouseResourceAmount(aBarracks, 16) >= 0) then begin
					Dec(Equipped[States.UnitOwner(aUnitID)]);
					Actions.UnitKill(aUnitID, True);
					Actions.HouseAddWaresTo(aBarracks, 16, 1);
					Actions.HouseAddWaresTo(aBarracks, 18, 1);
					Actions.HouseAddWaresTo(aBarracks, 20, 1);
					Actions.HouseAddWaresTo(aBarracks, 26, 1);
					Actions.HouseBarracksGiveRecruit(aBarracks);
										end;
					end;
			end;
		end;
end;

end;
end;


//Enable Repair button gives 1 ironshield + 1woodenshield + 1Leather jacket to the barrack to be able to train TH units.
//Disable repair button removes the previous items.
//this function removed already because OnTick slows downa the script.

//most of these need because the units have to be trainable in groups. The value of the wares is now 5. This value has to match at the OnWariorEquipe sector. Blockinck trades od LJ,WS,AX


Procedure OnHouseBuilt(aHouseID: Integer);
var H: integer;
Begin
	//if (BuildOrderH = 1) then      //its school opens the quarry and inn together, quarry opens the Wcutter.
			if States.HouseType(aHouseID) = 13 then //unlock inn after school
				Actions.HouseAllow(States.HouseOwner(aHouseID), 27, True);
			if States.HouseType(aHouseID) = 13 then //!!!unlock quarry-->skip the inn is possible. Original value was 27
				Actions.HouseAllow(States.HouseOwner(aHouseID), 14, True);
			if States.HouseType(aHouseID) = 14 then //unlock cutter
				Actions.HouseAllow(States.HouseOwner(aHouseID), 9, True);
			if States.HouseType(aHouseID) = 18 then begin		//TH as building
				Actions.HouseDeliveryBlock(aHouseID, True);		//because gold can be taken inot it...
				THx[States.HouseOwner(aHouseID)] := States.HousePositionX(aHouseID);
				THy[States.HouseOwner(aHouseID)] := States.HousePositionY(aHouseID);
				inc(THCounter[H]);
				end;
			if States.HouseType(aHouseID) = 21 then begin		
			//add the necesarry wares to the barrack, without these the players wuld have problem with training theTHunits without leather production
				BarracksList[States.HouseOwner(aHouseID)] := aHouseID;  	//Usng the full tags of the variables -
				Actions.HouseAddWaresTo(aHouseID, 16, WS);
				Actions.HouseAddWaresTo(aHouseID, 20, AX);
				Actions.HouseAddWaresTo(aHouseID, 18, LJ);
				H := States.HouseOwner(aHouseID);
				inc(BarrackCounter[H]);
						if BarrackCounter[H] > 0 then
							begin
							Actions.SetTradeAllowed(H,20,false);
							Actions.SetTradeAllowed(H,18,false);
							Actions.SetTradeAllowed(H,16,false);
								
						end;
			end;
end;



Procedure OnHouseDestroyed(aHouseID, aHouseDestroyerIndex: Integer);
var B, TX, TY: integer;   		//THCC-TH counter only for this block, more exact, calculate only witht the ready buildings
//var TXX, TYY, TID, THCC: integer;   //tried to fixing the multiple TH case when destroyed the last TH. Setting new coordinates.
	begin
		if States.HouseType(aHouseID) = 21 then begin
			B := States.HouseOwner(aHouseID);
			dec(BarrackCounter[B]);
					//if BarrackCounter[B] <= 0 then  //deleted because if delete the empty barrack than can abuse the trades. Simply disable those trades after 2nd barrack
					//		Actions.SetTradeAllowed(B,20,true);
					//		Actions.SetTradeAllowed(B,18,true);
					//		Actions.SetTradeAllowed(B,16,true);
					end;
							
		
		if States.HouseType(aHouseID) = 18 then begin
			B := States.HouseOwner(aHouseID);
			dec(THCounter[B]);
				THx[States.HouseOwner(aHouseID)] := -1;
				THy[States.HouseOwner(aHouseID)] := -1;
				
				//Relocate THx and THY
				//THCC := States.HouseMultipleTypeCount(B, 18);
				//If THCounter[B] > -1 then
				//TXX:= States.HousePositionX(aHouseID);
				//TYY:= States.HousePositionY(aHouseID);
				//TID := States.ClosestHouse(B, THx[B], THy[B], 18);
				//if TID <> -1 then
				//THx[B] := States.HousepositionX(TID);
				//THy[B] := States.HousepositionX(TID);
			end;
		
	end;
	
//adjusting the markettrades if the player doesnt have enough resource to trade LJ,AX,WS, then it has to not happen;
//procedure OnMarketTrade(aMarket:Integer; aForm: Integer; aTo: Integer);	
//var G:integer;
//	begin
//		G:= States.HouseOwner(aMarket);
//		if aForm = 20 then begin
//			if States.StatResourceProducedCount(G,20) - ((BarrackCounter[G] * 100)) < 0 then begin
//			
//			Actions.MarketSetTrade(aMarket,20,aTo,0);
//			end;
//		end;
//		
//	end;



procedure OnTick;
var P: Integer;
   begin
 
        if States.GameTime = 200 then					//the messages and instructions sent to players. They don't use to read pdf.
      Actions.ShowMsg(-1, '<$0>');						//welcome message  how  to f....p;)
	   if States.GameTime = 210 then
      Actions.ShowMsg(-1, '<$1>');
	    if States.GameTime = 220 then
      Actions.ShowMsg(-1, '<$2>');
	  if States.GameTime = 230 then
      Actions.ShowMsg(-1, '<$3>');
	  
	    for P := 0 to  7 do
		if (States.GameTime + P*2) mod 10 = 0 then
			UpdateOverlay(States.GameTime, P);
				
			//if States.StatResourceProducedCount(P,20) > 0 then   //if not enough produced AX are there
			//Actions.SetTradeAllowed(P,20,false);
				
			//	if States.StatResourceProducedCount(P,20)-((BarrackCounter[P] * AX)) > 0 then 
			//	Actions.SetTradeAllowed(P,20,true);
			
	end;