--Required control rate.
control_rate = 2

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

  -- Running pilot has healed up some.
  if task == "runaway" then
    if parmour() == 100 then
      -- "attack" should be called after "runaway".
      poptask()
    end

    -- Nothing to do.
  elseif task ~= "attack" and task ~= "runaway" then
    -- If getenemy() is 0, there is no enemy around.
    enemy = getenemy()
    if parmour() == 100 and enemy ~= 0 then
      -- Taunts.
      num = rng(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
      comm(enemy,msg)

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

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

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

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

function taunt(target)
  num = rng(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 comm(target, msg) end
end

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

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

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

-- Attack the target.
function attack()
  target = gettargetid()

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

  dir = face(target)
  dist = getdist(getpos(target))

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

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