function findNearbyEmptyBlock(startingpos)
	local pos
	
	-- Start at the level the player died, then work our way upwards
	for extraverticaloffset = 0,15 do
		-- Search in a 3x3 horizontal region
		-- We want to maximise the chances of finding two consecutive positions that are next to each other (so a double-chest can be placed).  To do this we search in a spiral/circular pattern, not a linear search.
		local offsets3x3 = { Vec3(0,0,0), Vec3(1,0,0), Vec3(1,0,-1), Vec3(0,0,-1), Vec3(-1,0,-1), Vec3(-1,0,0), Vec3(-1,0,1), Vec3(0,0,1), Vec3(1,0,1) }
		for _,offset in pairs(offsets3x3) do
			pos = startingpos + offset + Vec3(0,extraverticaloffset,0)
			if blockIsEmpty(pos) then return pos; end
		end
	end
	
	-- Give up, we can't find anything good.  Replace whatever block they landed on, destroying it.
	return startingpos
end

function blockIsEmpty(pos)
	-- Players won't mind these blocks getting destroyed/replaced with something like a chest.
	-- We don't want to replace something that will give them a sense of loss, like diamond blocks, obsidian, redstone or another chest.
	local emptyBlocks = {"air", "water", "lava", "portal"} 
	
	spell.pos = pos
	for _,blocktype in pairs(emptyBlocks) do
		if spell.block.type.id == blocktype then return true; end
	end
	return false
end

	
	
	



function deathChest(event)
	if event.entity.type.id ~= "player" then return true; end
	--if event.entity.gamemode ~= "survival" then return true; end
	
	
	
	local chest1pos = findNearbyEmptyBlock(event.entity.pos)
	spell.pos = chest1pos
	spell.block = Block:new("chest")
	
	local chest2pos = findNearbyEmptyBlock(event.entity.pos)
	spell.pos = chest2pos
	spell.block = Block:new("chest")
	
	print(chest1pos)
	print(chest2pos)
	
	--for _,invitem in pairs(event.entity.nbt.Inventory) do
	--	spell.blockEntity:putNbt({ Items = {invitem} })
	--end
	
	--spell.blockEntity:putNbt({ Items = {{Slot=0, count=13, id="minecraft:egg"}} })
	--print(inspect(spell.blockEntity.nbt.Items))
	
end

spell:intercept({"BeforeLivingEntityDeathEvent"}, deathChest)


