--Required control rate.
control_rate = 2

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

  -- Running pilot has healed up some.
  if task == "runaway" then
    if ai.parmour() == 100 then
      -- "attack" should be called after "runaway".
      ai.poptask()
  elseif ai.dist(ai.pos(ai.targetid())) > 300 then
   ai.hyperspace()
    end

    -- Nothing to do.
  elseif task ~= "attack" and task ~= "runaway" then
    -- If getenemy() is 0, there is no enemy around.
    enemy = ai.getenemy()
    if ai.parmour() == 100 and enemy ~= 0 then
      -- Taunts.
      num = ai.rnd(0,4)
      if num == 0 then msg = "Prepare to be boarded!"
      elseif num == 1 then msg = "Whoa! Lookie what we found here!"
      elseif num == 2 then msg = "What's a ship like you doing in a place like this?"
      end
      ai.comm(enemy,msg)

      -- Make hostile to the enemy (mainly, player! YOU!).
      ai.hostile(enemy)

      -- Go ahead and attack.
      ai.combat() -- Set to be in combat.
      ai.pushtask(0, "attack", enemy) -- Begin the attack.
    -- Nothing to attack.
    else
      ai.pushtask(0, "fly")
    end
  end
end

-- Required "attacked" function
function attacked(attacker)
  task = ai.taskname()

  -- Pirate isn't fighting or fleeing already.
  if task ~= "attack" and task ~= "runaway" then
    taunt(attacker)
    ai.pushtask(0, "attack", attacker)
  -- Pirate is fighting bit switches to new target (doesn't forget the old on though).
  elseif task == "attack" then
    if ai.targetid() ~= attacker then
      ai.pushtask(0, "attack", attacker)
    end
  end
end

function create()
 if ai.rnd(0,5) ~= 0 then
  ai.setcredits(0, ai.shipprice()/300)
 end
end

function taunt(target)
  num = ai.rnd(0,4)
  if num == 0 then msg = "How dare you attack me?!"
  elseif num == 1 then msg = "Aha! You think you can best ME?!"
  elseif num == 2 then msg = "JUST! DIE!"
  elseif num == 3 then msg = "Ohh, You're not going to enjoy this!"
  end
  if msg then ai.comm(target, msg) end
end

-- Run away from the target.
function runaway()
  target = ai.targetid()

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

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

-- Attack the target.
function attack()
  target = ai.targetid()

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

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

  -- We need to know when to run away.
  if ai.parmour() < 70 then
    ai.pushtask(0, "runaway", target)
  -- Try to obliterate the target.
  elseif dir < 10 and dist > 300 then
    ai.accel()
  elseif dir < 10 and dist < 300 then
    ai.shoot()
  end
end

-- Fly to the player. Pointless until hyperspace is implemented.
function fly()
  target = player
  dir = ai.face(target)
  dist = ai.dist(ai.pos(target))
  if dir < 10 and dist > 300 then
    ai.accel()
  end
end