-- Required control rate
control_rate = 2

-- Required "control" function.
function control()
 task = ai.taskname()

 enemy = ai.getenemy()
 if task ~= "attack" and enemy ~= 0 then
  ai.pushtask(0, "attack", enemy)
 elseif ai.taskname() == "none" then
  ai.pushtask(0, "scan", ai.rndpilot())
 end
end

-- Required "attacked" function
function attacked(attacker)
 task = ai.taskname()
 if task ~= "attack" and task ~= "runaway" then
  -- Some taunting.
  taunt(attacker)

  -- Now pilot fights back!
  ai.pushtask(0, "attack", attacker)

 elseif task == "attack" then
  if ai.targetid() ~= attaker then
   ai.pushtack(0, "attack", attacker)
  end
 end
end

function create()
 ai.setcredits(ai.rnd(1000, ai.shipprice()/200))
 if ai.rnd(0, 2)==0 then
  ai.broadcast("This area is under militia survellance.")
  end
end

-- Taunts
function taunt(target)
 num = ai.rnd(0,4)
 if num == 0 then msg = "How dare you attack me!?"
 elseif num == 1 then msg = "YOU! ARE NOT! PREPARED!!"
 elseif num == 2 then msg = "Won't You just die already!?"
 elseif num == 3 then msg = "You won't survive!"
 end
 if msg then ai.comm(attacker, msg) end
end

function runaway()
 target = ai.targetid()

 -- Make sure pilot exists.
 if not ai.exists(target) then
  ai.poptask()
  return
 end

 dir = ai.face(target, 1)
 ai.accel()
end

function attack()
 target = ai.targetid()

 if not ai.exists(target) then
  ai.poptask()
  return
 end

 dir  = ai.face(target)
 dist  = ai.dist(ai.pos(target))
 second = ai.secondary()

 if ai.secondary() == "Launcher" then
  ai.settarget(target)
  ai.shoot(2)
 end

 if ai.parmour() < 70 then
  ai.poptask()
  ai.pushtask(0, "runaway", target)
 elseif dir < 10 and dist > 300 then
  ai.accel()
 elseif dir < 10 and dist < 300 then
  ai.shoot()
 end
end

function scan()
 target = ai.targetid()
 if not ai.exists(target) then
  ai.poptask()
  return
 end
 dir = ai.face(target)
 dist = ai.dist(ai.pos(target))
 if dir < 10 and dist > 300 then
  ai.accel()
 elseif dist < 300 then -- Scan the target.
  ai.poptask()
 end
end