print("biara vs raelag")

rnd = 0;
d = GetGameVar("C6M5_diff") + 0;
death = 0
charge_count = 0;
forget = 0;
slow = 0;
dark = 0;

enemy_id = {14, 56, 70, 84, 82, 12, 50, 8, 48, 68, 66, 4, 80, 78, 10, 64, 58, 74, 72};

function Prepare()
	EnableCinematicCamera(nil);
	sleep(10);
	SummonCreature(DEFENDER, 20, 55 + d * 5, 7, 12);
	sleep(10);
	SummonCreature(DEFENDER, 20, 65 + d * 5, 7, 8);
	sleep(10);
	SummonCreature(DEFENDER, 20, 55 + d * 5, 7, 3);
	sleep(15);
end

function Start() 
	units = GetCreatures(ATTACKER);
	for i, unit in units do
		rnd = rnd + GetCreatureNumber(unit);
	end;
	units = GetCreatures(DEFENDER);
	for i, unit in units do
		rnd = rnd + GetCreatureNumber(unit);
	end;
	EnableAutoFinish(nil);
	sleep(30);
	SummonCreature(DEFENDER, 22, 50 + d * 5, 13, 3);
	sleep(10);
	SummonCreature(DEFENDER, 22, 50 + d * 5, 13, 12);
	sleep(10);
	EnableCinematicCamera(not nil);
end

function DefenderCreatureDeath()
	rnd = rnd + 1;
	death = death + 1
	if death == 1 then
		sleep(10);
		SummonCreature(DEFENDER, 26, 30 + d * 5, 12, 8);
	end
	if death == 2 then
		sleep(10);
		SummonCreature(DEFENDER, 27, 10 + d * 5, 7, 12);
		sleep(10);
		SummonCreature(DEFENDER, 27, 10 + d * 5, 7, 3);
		sleep(1);
	end
	local defenders = GetDefenderCreatures();
	if (length(defenders) == 0) then Finish(ATTACKER) end;
end

function AttackerCreatureDeath()
	rnd = rnd + 1;
	local attackers = GetAttackerCreatures();
	if (length(attackers) == 0) then Finish(DEFENDER) end;
end

function DefenderHeroMove(hero)
	rnd = rnd + 1;
	result = biara_turn(hero);
	return result
end

function biara_turn(hero)
	units = GetCreatures(ATTACKER);
	if charge_count == 0 and d > 1 and randm(4) == 0 then
		victim = GetTarget(ATTACKER, enemy_id);
		if victim ~= nil then
			startThread(cast, hero, 56, victim);
			charge_count = 1;
			return not nil
		end;
	end;
	if dark < 2 and d > 1 and randm(5) == 0 then
		UnitCastGlobalSpell(hero, 21);
		dark = dark + 1;
		return not nil
	end;
	if forget == 0 and d > 1 and randm(6) == 0 then
		UnitCastGlobalSpell(hero, 213);
		forget = 1;
		return not nil
	end;
	if slow == 0 and d > 1 and randm(6) == 3 then
		UnitCastGlobalSpell(hero, 212);
		slow = 1;
		return not nil
	end;
	return nil
end;

function cast(hero, spell, target)
	UnitCastAimedSpell(hero, spell, target);
	print("casting spell "..spell);
end;

function GetTarget(side, array)
	local units = GetCreatures(side);
	for i, id in array do
		for j, unit in units do
			if GetCreatureType(unit) == id then
				return unit;
			end;
		end;
	end;
	return nil;
end;

function DefenderCreatureMove(unit)
	rnd = rnd + 1;
end;

function AttackerHeroMove(hero)
	rnd = rnd + 1;
end;

function AttackerCreatureMove()
	rnd = rnd + 1;
end;

function randm(num)
	local rand = rnd;
	if rand >= num then
		rand = mod(rand, num);
	end;
	return rand;
end;