-- Required control rate.
control_rate = 2

-- Required "control" function.
function control()
  if taskname() == "none" then
    planet = getrndplanet()
    pushtask(0, "go", planet)
  end
end

-- Required "attacked" function.
function attacked(attacker)
  if taskname() ~= "runaway" then
    -- Let's have some messages.
    num = rng(0,3)
    if num == 0 then msg = "Mayday! We are under attack!"
    elseif num == 1 then msg = "Requesting assistance! Some scoundral is attacking us!"
    elseif num == 2 then msg = "Merchant vessle under attack here! HALP!"
    end
    if msg then broadcast(msg) end

    -- So bravely run away!
    pushtask(0, "runaway", attacker)
  end
end

-- Runs away.
function runaway()
  target = gettargetid()
  dir = face(target, 1)
  accel()
end

-- Fly to the target.
function go()
  target = gettarget()
  dir = face(target)
  dist = getdist(target)
  bdist = minbrakedist()
  if dir < 10 and dist > bdist then
    accel()
  elseif dir < 10 and dist < bdist then
    poptask()
    pushtask(0, "stop")
  end
end

-- Backthrust.
function stop()
  brake()
  if isstopped() then
    poptask()
    settimer(0, rng(8000, 15000))
    pushtask(0, "land")
  end
end

--Waits.
function land()
  if timeup(0) then
    pushtask(0, "runaway", player)
  end
end