local resetCaptureTargets, isCaptureTarget = (function()

	local captureTargets

	mn.LuaSEXPs['set-capture-target'].Action = function(value, ...)
		for _, v in ipairs({...}) do
			captureTargets[tostring(v[1])] = value
		end
	end

	return function()
		captureTargets = {}
		for k, v in pairs(mn.CustomData) do
			if k:find('^CaptureTarget') then captureTargets[v] = true end
		end
	end, function(ship)
		-- "== true" maps both nil and false to false
		return captureTargets[tostring(ship)] == true
	end

end)()

local rewriteOrders = (function()

	local replacements = {
		ORDER_DISABLE_TACTICAL = ORDER_DISABLE,
		ORDER_DISARM_TACTICAL = ORDER_DISARM,
	}

	local function getReplacementType(order)
		local orderType = order:getType()
		if orderType == ORDER_DISABLE_TACTICAL then
			return ORDER_DISABLE
		elseif orderType == ORDER_DISARM_TACTICAL then
			return ORDER_DISARM
		else
			return nil
		end
	end

	local function list(orders)
		local orderList = {}
		-- shiporders handles don't support pairs/ipairs.
		local count = #orders
		for i = 1, count do table.insert(orderList, orders[i]) end
		return orderList
	end

	local function rewriteOrdersForShip(ship)
		-- Iterate a copy of the ship's orders since we're modifying it.
		for _, order in ipairs(list(ship.Orders)) do
			local replacement = getReplacementType(order)
			local target = order.Target
			if replacement and isCaptureTarget(target) then
				-- Capture the priority before remove() invalidates it.
				local priority = order.Priority
				order:remove()
				-- For some reason, giveOrder() takes the priority as a percent.
				ship:giveOrder(replacement, target, nil, priority/100)
			end
		end
	end

	return function()
		for ship in mn.getShipList() do
			rewriteOrdersForShip(ship)
		end
	end

end)()

return {reset = resetCaptureTargets, check = rewriteOrders}

