

give_initial_stuff = {
	items = {}
}
local volatile_positions = {}

function give_initial_stuff.give(player)
	minetest.log("action",
			"Giving initial stuff to player " .. player:get_player_name())
	local inv = player:get_inventory()
	for i, stack in pairs(give_initial_stuff.items) do
		local s = inv:set_stack("main", i, stack)
	end
end

function give_initial_stuff.add(stack, prefered_position)
	local items = give_initial_stuff.items
	local volatile
	if not prefered_position
	then
		volatile = true
		
		--count to first empty slot
		prefered_position = 1
		while true
		do
			if items[prefered_position]
			then
				prefered_position = prefered_position + 1
			else
				break
			end
		end
	end
	
	while true
	do
		if items[prefered_position]
		then
			if volatile_positions[prefered_position] and not volatile
			then
				local s = items[prefered_position]
				items[prefered_position] = ItemStack(stack)
				stack = s
				volatile_positions[prefered_position] = nil
				volatile = true
			end
			prefered_position = prefered_position + 1
		else
			items[prefered_position] = ItemStack(stack)
			if volatile
			then
				volatile_positions[prefered_position] = true
			end
			break
		end
	end
end

function give_initial_stuff.clear()
	give_initial_stuff.items = {}
end

function give_initial_stuff.add_from_csv(str)
	local items = str:split(",")
	for _, itemname in ipairs(items) do
		give_initial_stuff.add(itemname)
	end
end

function give_initial_stuff.set_list(list)
	give_initial_stuff.items = list
end

function give_initial_stuff.get_list()
	return give_initial_stuff.items
end

--give_initial_stuff.add_from_csv(stuff_string)
if minetest.settings:get_bool("give_initial_stuff") then
	minetest.register_on_newplayer(give_initial_stuff.give)
end
