-- LUALOCALS < ---------------------------------------------------------
-- SKIP: get_mod_api include
local error, loadfile, minetest, pairs, rawget, rawset, string, unpack,
      vector
    = error, loadfile, minetest, pairs, rawget, rawset, string, unpack,
      vector
local string_sub
    = string.sub
-- LUALOCALS > ---------------------------------------------------------

local function shareglobal(name, thing)
	return rawget(_G, name) or rawset(_G, name, thing)
end

do
	local included = {}
	shareglobal("include", function(n)
			local modname = minetest.get_current_modname()
			local modpath = minetest.get_modpath(modname)
			local found = included[n]
			if found ~= nil then return unpack(found) end
			local func, err = loadfile(modpath .. "/" .. n .. ".lua")
			if not func then return error(err) end
			found = {func(include)}
			included[n] = found
			return unpack(found)
		end)
end

shareglobal("get_mod_api", function()
		local modname = minetest.get_current_modname()
		local api = rawget(_G, modname) or {}
		rawset(_G, modname, api)
		return api
	end)
get_mod_api()

shareglobal("startswith", function(str, pref) return string_sub(str, 1, #pref) == pref end)

shareglobal("posrel", function(pos, round)
		pos = round and vector.round(pos) or pos
		return function(...) return vector.add(pos, vector.new(...)) end
	end)

shareglobal("addgroups", function(name, ...)
		local def = minetest.registered_items[name] or error(name .. " not found")
		local groups = {}
		for k, v in pairs(def.groups) do
			groups[k] = v
		end
		local function addall(x, ...)
			if not x then return end
			groups[x] = 1
			return addall(...)
		end
		addall(...)
		return minetest.override_item(name, {groups = groups})
	end)
