local compressed_sound = default.node_sound_dirt_defaults()

local nb_iterations = 3

local function add_one_compression(p)
  def = {
    description = p["desc"],
    tiles = p["img"],
    groups = {dig_immediate=3},
    is_ground_content = false,
    sounds = compressed_sound
  }
  minetest.register_node(p["name"], def)
  
  recipe = {}
  for i=1,8 do
    recipe[i]=p["base"]
  end
  
  minetest.register_craft({
    output = p["name"],
    type = "shapeless",
    recipe = recipe
  })
  
  minetest.register_craft({
    output = p["base"].." 8",
    type = "shapeless",
    recipe = {p["name"]}
  })
end

local function shallow_copy(t)
  local t2 = {}
  for k,v in pairs(t) do
    t2[k] = v
  end
  return t2
end

local function mark_texture(t, i)
  mark = "^(compresser_"..i..".png^[opacity:200)"
  t = shallow_copy(t)
  if t["name"] then
    t["name"] = t["name"]..mark
  else
    k = 1
    while t[k] do
      t[k] = t[k]..mark
      k = k+1
    end
  end
  return t
end

local function add_compressions(p, n)
  -- Assume n>=1
  basenode = minetest.registered_nodes[p["base"]]
  p["img"] = basenode.tiles
  add_one_compression({
      desc="\27(compressed)8 "..p["description"],
      name="compresser:compressed1_"..p["name"],
      base=p["base"],
      img=mark_texture(p["img"],1)
    })
  for i=2,n do
    add_one_compression({
      desc="\27(compressed)8^"..i.." "..p["description"],
      name="compresser:compressed"..i.."_"..p["name"],
      base="compresser:compressed"..(i-1).."_"..p["name"],
      img=mark_texture(p["img"],i)
    })
  end
end

local function add_compressions_helper(base)
  basenode = minetest.registered_nodes[base]
  pos_col,_ = string.find(base,":")
  desc = basenode.description
  desc = desc:gsub("\27E", "")
  desc = desc:gsub("\27%(%w*@?%w*%)", "") -- Or keep it maybe?
  add_compressions({
    description=desc,
    name=string.sub(base,pos_col+1),
    base=base
  },nb_iterations)
end

local to_compress_default = {
"glass", "dirt", "stone",
"cobble", "gravel",
"bronzeblock", "coalblock", "copperblock", "diamondblock", "goldblock", "mese_block", "obsidian_block", "steelblock", "tinblock", "stone_block", "sandstone_block", "sand",
"acacia_tree", "tree","silver_sand", "silver_sandstone", "silver_sandstone_brick", "aspen_tree", "pine_tree", "acacia_wood", "wood", "aspen_wood", "pine_wood"
}

for _,p in ipairs(to_compress_default) do
  add_compressions_helper("default:"..p)
end

for i=1,nb_iterations do
  n = minetest.registered_nodes["compresser:compressed"..i.."_glass"]
  n = shallow_copy(n)
  n.drawtype = "glasslike_framed_optional"
  n.paramtype = "light"
  minetest.register_node("compresser:compressed"..i.."_glass", n)
  -- Doesn't work by modifying directly, I don't know why.
end
