local tracker

local function reset()
  tracker = {}
end

local function getStatus(ship, oldStatus)
  if ship.Disabled or ship.Class.Name == 'PVC Aten#Hulk' then
    return false
  end
  local physics = ship.Physics
  -- If the ship is actively thrusting forward, start its thruster glow.
  -- We check this instead of speed to avoid false positives from collisions.
  if physics.ForwardThrust > 0.01 or ship:isWarpingStage2() or ship:isDepartingWarp() then
    return true
  end
  -- If the ship has come to a complete stop, cancel its thruster glow.
  if physics:getForwardSpeed() < 1 then
    return false
  end
  -- New ships default to true (unless they're still to start with).
  if oldStatus == nil then
    return true
  end
  -- Everything else is unchanged. This means that decelerating ships keep their
  -- thruster glows active, which isn't realistic, but looks right in practice.
  return oldStatus 
end

local function updateShip(ship)
  local signature = ship:getSignature()
  local oldStatus = tracker[signature]
  local newStatus = getStatus(ship, oldStatus)
  if oldStatus ~= newStatus then
    tracker[signature] = newStatus
    ship:setFlag(not newStatus, 'no-thrusters')
  end
end

local function update()
  for ship in mn.getShipList() do
    updateShip(ship)
  end
end

return { update = update, reset = reset }

