local fdir_table = {
   {  1,  0 },
   {  0, -1 },
   { -1,  0 },
   {  0,  1 },
   {  1,  0 },
   {  0, -1 },
   { -1,  0 },
   {  0,  1 },
}

function ls_core.space_to_side(pos, placed_node)
   local node = core.get_node(pos)
   local fdir = node.param2 % 32
   local pos2 = {x = pos.x + fdir_table[fdir+1][1], y=pos.y, z = pos.z + fdir_table[fdir+1][2]}
   local node2 = core.get_node(pos2)
   local node2def = core.registered_nodes[node2.name] or nil
   if not node2def.buildable_to then
      return false
   else
      local placed_node = placed_node or 'ls_core:empty'
      core.set_node(pos2,{name = placed_node, param2=fdir})
      return true
   end
end

function ls_core.remove_side_node(pos, oldnode)
   local fdir = oldnode.param2 % 32
   local pos2 = {x = pos.x + fdir_table[fdir+1][1], y=pos.y, z = pos.z + fdir_table[fdir+1][2]}
   local node2 = core.get_node(pos2).name
   if core.get_item_group(node2, 'empty_node') > 0 then
      core.remove_node(pos2)
   end
end

function ls_core.space_on_top(pos)
   local above = {x = pos.x, y = pos.y + 1, z = pos.z}
   local top_node = core.get_node(above)
   local top_def = core.registered_nodes[top_node.name] or nil
   if not top_def.buildable_to then
      return false
   else
      core.set_node(above,{name='ls_core:empty'})
      return true
   end
end

function ls_core.remove_top_node(pos)
   local above = {x = pos.x, y = pos.y + 1, z = pos.z}
   local top_node = core.get_node(above).name
   if core.get_item_group(top_node, 'empty_node') > 0 then
      core.remove_node(above)
   end
end

function ls_core.space_to_front(pos)
   local node = core.get_node(pos)
   local fdir = node.param2 % 32
   local pos2 = {x = pos.x + fdir_table[fdir+4][1], y=pos.y, z = pos.z + fdir_table[fdir+4][2]}
   local node2 = core.get_node(pos2)
   local node2def = core.registered_nodes[node2.name] or nil
   if not node2def.buildable_to then
      return false
   else
      core.set_node(pos2,{name = 'ls_core:empty'})
      return true
   end
end

function ls_core.remove_front_node(pos, oldnode)
   local fdir = oldnode.param2 % 32
   local pos2 = {x = pos.x + fdir_table[fdir+4][1], y=pos.y, z = pos.z + fdir_table[fdir+4][2]}
   local node2 = core.get_node(pos2).name
   if core.get_item_group(node2, 'empty_node') > 0 then
      core.remove_node(pos2)
   end
end

function ls_core.inv_slot_bg(x,y,w,h)
   local w = w or 1
   local h = h or 1
   local string = ''
   local offset_x = 0
   local offset_y = 0
   for ih = 1, h do
      for iw = 1, w do
         string = string..
         'image['..x+offset_x..','..y+offset_y..';1,1;ls_core_slot_bg.png]'
         offset_x = iw*1.25
      end
      offset_x = 0
      offset_y = ih*1.25
   end
   return string
end

function ls_core.add_inv(player, item)
   local player_inv = player:get_inventory()
   if player_inv:room_for_item('main', item) then
      player_inv:add_item('main', item)
   else
      local drop_pos = player:get_pos()
      core.add_item(drop_pos, item)
   end
end
