local modname
if minetest
then
	modname = minetest.get_current_modname()
else
	modname = "inventory_populator"
end

_G[modname] = {}

--[[
{
	rolls = <number>,
	rolls_max = <number or nil>
	loots = --array part of table sorted from heighest weight to lowest
	{
		{
			weight = <number>,
			loot = <itemstring or loot table>,
			repetitions = <number>,
			repetitions_max = <number or nil>,
		},
		.
		.
		.
		accumulated_weight = <number>,
	}
}
]]

--returns table of ItemStacks
local function get_items(loot_table, rand, max_stacks, items)
	items = items or {}
	max_stacks = max_stacks or math.huge
	local loots = loot_table.loots
	for i = 1, rand:next(loot_table.rolls, loot_table.rolls_max or loot_table.rolls)
	do
		local roll = rand:next(1, loots.accumulated_weight)
		for k, v in ipairs(loots)
		do
			roll = roll - v.weight
			if roll < 1
			then
				local reps = rand:next(v.repetitions, v.repetitions_max or v.repetitions)
				if type(v.loot) == "string"
				then
					local stack = ItemStack(v.loot)
					stack:set_count(stack:get_count() * reps)
					items[#items + 1] = stack
				elseif type(v.loot) == "table"
				then
					local loot = v.loot
					for i = 1, reps
					do
						get_items(loot, rand, max_stacks, items)
						if #items >= max_stacks
						then
							--cull loot table
							for i = max_stacks + 1, #items
							do
								items[i] = nil
							end
							break
						end--if
					end--for
				end--if
				break
			end--if
		end--for
		if #items >= max_stacks
		then
			break
		end
	end--for
	return items
end

local function get_inv_list(list_size, loot_table, rand)
	local items = get_items(loot_table, rand, list_size)
	local free_spaces = list_size - #items
	for i = 1, free_spaces
	do
		local pos = rand:next(1, list_size)
		table.insert(items, pos, nil)
	end
	return items
end

_G[modname].get_inv_list = get_inv_list
_G[modname].get_items = get_items
