if not turtle or not turtlex then
  print("Can only run on a turtle equiped with turtlex.")
  return
end

turtlex.updateInventory()

local inv=turtlex.getInventory()

term.clear()

term.setCursorPos(1,1)
term.write("Use arrows to select, enter to edit")

term.setCursorPos(1,2)
term.write("space to update, tab to exit")

local selected=1

local function showItem(index)
  if index==selected then
    term.setCursorPos(3,12)
    term.clearLine()
    if inv.slots[index].quantity~=0 then
      term.write(inv.slots[index].type)
    end
    term.setTextColor(colors.black)
    term.setBackgroundColor(colors.white)
  else
    term.setTextColor(colors.white)
    term.setBackgroundColor(colors.black)
  end

  term.setCursorPos(((index-1)%2)*20+1,math.floor((index-1)/2)+4)
  local str=string.format("%2d ",index)
  
  if inv.slots[index].quantity==0 then
    str=str.."empty"
  else
    str=str..string.format("%2d ",inv.slots[index].quantity)..inv.slots[index].type
  end
  
  if #str>=19 then
    str=str:sub(1,16).."..."
  else
    str=str..string.rep(" ",19-#str)
  end  
  write(str)
  if index==selected then
    term.setTextColor(colors.white)
    term.setBackgroundColor(colors.black)
  end
end

function showAll()
  for i=1,16 do
    showItem(i)
  end
end

showAll()

while true do
  local e={os.pullEvent()}
  if e[1]=="key" then
    local prev=selected
    if e[2]==keys.down then
      selected=selected+2
      if selected>16 then selected=selected-16 end
    elseif e[2]==keys.up then
      selected=selected-2
      if selected<1 then selected=selected+16 end
    elseif e[2]==keys.left or e[2]==keys.right then
      local odd=selected%2==1
      if odd then
        selected=selected+1
      else
        selected=selected-1
      end
    elseif e[2]==keys.space then
      turtlex.updateInventory()
      showAll()      
    elseif e[2]==keys.enter then
      if inv.slots[selected].quantity~=0 then
        term.setCursorPos(2,12)
        term.clearLine()
        os.queueEvent("key",keys.up)
        local name=read(nil,{inv.slots[selected].type})
        if name~="" then
          turtlex.setItemType(name,selected)
          showAll()        
        end
      end
    elseif e[2]==keys.tab then
      break
    end
    
    if selected~=prev then
      showItem(prev)
      showItem(selected)
    end    
  end
end
term.setTextColor(colors.white)
term.setBackgroundColor(colors.black)
term.setCursorPos(1,13)
print()