--[[     gtRemote      ]]--
--[[      by Dog       ]]--
--[[ aka HydrantHunter ]]--
--[[  with assistance  ]]--
--[[   from CometWolf  ]]--
--[[ pastebin XQQsRyLX ]]--
local gtRver = "1.1.17"
--[[
Tested with/requires:
  - Mincraft 1.6.4 or 1.7.10
  - ComputerCraft 1.63+
    - 1 Advanced Wireless Pocket Computer
    - gtHost running on one or more Wireless Turtles (standard or advanced)
]]--
-- AUTOMATIC/STATIC CONFIGURATION
 -- Default Settings
local netSide, runState, tDirection, err = "none", "init", "Forward", "NO"
local drawCLI, turtleInventory, tmpState, pollTimer, tEdit, colorX, word, curX, curY
local kernelState, timerDelay, postponedSort, inputting = false, false, false, false
local termX, termY = term.getSize()
 -- Turtle List
local allTurtles, filteredTurtles, newSettings = { }, { }, { }
local numPages, pageNum = 1, 1
local fuelFilter, showFuel, removal = false, false, false
local gtHost, thisTurtle
 -- Color Definitions
local white = colors.white
local black = colors.black
local silver = colors.lightGray
local gray = colors.gray
local brown = colors.brown
local yellow = colors.yellow
local orange = colors.orange
local red = colors.red
local magenta = colors.magenta
local purple = colors.purple
local blue = colors.blue
local sky = colors.lightBlue
local cyan = colors.cyan
local lime = colors.lime
local green = colors.green
-- END AUTOMATIC/STATIC CONFIGURATION
 
local function filterTurtleList()
  filteredTurtles = { }
  local turtleCount = 1
  for i = 1, #allTurtles, 1 do
    if fuelFilter then -- if fuelFilter is TRUE (gray) then show only non-fueled turtles
      if not allTurtles[i].fuelState then
        filteredTurtles[turtleCount] = allTurtles[i]
        filteredTurtles[turtleCount].atList = i
        turtleCount = turtleCount + 1
        if turtleCount > #allTurtles then break end
      end
    else              -- otherwise show fueled turtles
      if allTurtles[i].fuelState then
        filteredTurtles[turtleCount] = allTurtles[i]
        filteredTurtles[turtleCount].atList = i
        turtleCount = turtleCount + 1
        if turtleCount > #allTurtles then break end
      end
    end
  end
  numPages = math.max(1, math.ceil(#filteredTurtles / 24))
  if numPages < pageNum then pageNum = numPages end
end
 
local function sortTurtleList()
  for i = 1, #filteredTurtles, 1 do
    if gtHost == filteredTurtles[i].cc then    -- we're already on the list
      filteredTurtles[i] = newSettings         -- update remote with current state of host
      for j = 1, #allTurtles, 1 do
        if allTurtles[j].cc == filteredTurtles[i].cc then -- find turtle in allTurtles
          allTurtles[j] = newSettings          -- update entry with current state of host
          filteredTurtles[i].atList = j        -- set allTurtles ID for the filtered turtle
          break
        end
      end
      filterTurtleList()                       -- in case turtle runs out of fuel (?)
      drawCLI()
      return
    end
  end
  for i = 1, #allTurtles, 1 do
    if gtHost == allTurtles[i].cc then         -- we're already on the list
      allTurtles[i] = newSettings              -- update remote with current state of host
      filterTurtleList()                       -- in case fuel state changes (?)
      return
    end
  end
  if #allTurtles == 0 then                     -- the list is empty
    table.insert(allTurtles, newSettings)      -- add it
    filterTurtleList()
  else
    for i = 1, #allTurtles, 1 do
      if newSettings.name < allTurtles[i].name then -- alphabetize
        table.insert(allTurtles, i, newSettings) -- insert
        filterTurtleList()
        break
      end
      if i >= #allTurtles then                 -- we've reached the end of the list
        table.insert(allTurtles, newSettings)  -- tack it on
        filterTurtleList()
        break
      end
    end
  end
  if runState ~= "Help" then drawCLI() end
end
 
local function netSend(targetHost, cmd1, cmd2)
  local tempSettings = { program = "gtRemote", cmd = cmd1, action = cmd2, }
  if not rednet.isOpen(netSide) then
    rednet.open(netSide)
  end
  if targetHost == "ALL" then
    rednet.broadcast(tempSettings, "gtRemote")
  else
    rednet.send(targetHost, tempSettings)
  end
end
 
local function netReceive()
  local thisTurtleUpdated = false
  --while true do
    local id, message = rednet.receive()
    if type(message) == "table" and message.program == "gtRemoteHost" then
      gtHost = id
      newSettings = message
      if runState == "Remote" or runState == "Inventory" then -- If we're in a screen than can be updated with info
        if gtHost == allTurtles[thisTurtle].cc then           -- If it's the turtle we're working with
          allTurtles[thisTurtle] = newSettings                -- Update the turtle's info
          thisTurtleUpdated = true
        end
        postponedSort = true
        --sortTurtleList()
        if thisTurtleUpdated then
          if runState == "Remote" then
            drawCLI()
          elseif runState == "Inventory" then
            turtleInventory()
          end
          thisTurtleUpdated = false
        end
      else
        sortTurtleList()
        drawCLI()
      end
    end
  --end
end
 
local function assignColor(devNumber)
  local colorBurst = {
                       B = blue,
                       S = sky,
                       N = brown,
                       P = purple,
                       G = green,
                       O = orange,
                       R = red,
                       I = silver,
                     }
  for k, v in pairs(colorBurst) do
    if filteredTurtles[devNumber].color == tostring(k) then
      return v
    end
  end
end
 
local function assignMasterColor(devNumber)
  local colorBurst = {
                       B = blue,
                       S = sky,
                       N = brown,
                       P = purple,
                       G = green,
                       O = orange,
                       R = red,
                       I = silver,
                     }
  for k, v in pairs(colorBurst) do
    if allTurtles[devNumber].color == tostring(k) then
      return v
    end
  end
end
 
local function drawElement(x, y, w, h, txColor, bgColor, text)
  local deText = tostring(text)
  term.setCursorPos(x, y)
  if w == "OFF" then                   --
    term.setBackgroundColor(gray)      --
    term.write("  ")                   -- Switch (OFF)
    term.setBackgroundColor(red)       --
    term.write("  ")                   --
  elseif w == "ON" then                --
    term.setBackgroundColor(green)     --
    term.write("  ")                   -- Switch (ON)
    term.setBackgroundColor(gray)      --
    term.write("  ")                   --
  else
    if bgColor then term.setBackgroundColor(bgColor) end
    if w > #deText or h > 1 then       -- We're 'drawing' something more than text
      for i = 1, h, 1 do               --
        term.write(string.rep(" ", w)) -- Draw the 'element' (box/rectangle/line-seg)
        term.setCursorPos(x, y + i)    --
      end
    end
    if deText ~= "" and deText ~= "nil" then
      if txColor then term.setTextColor(txColor) end
      if w < #deText then w = #deText end -- Ensure minimum length
      local xW = (x + math.floor(w / 2)) - math.floor(#deText / 2) -- Center the text horizontally
      local xH = y + math.floor(h / 2)    -- Center the text vertically
      term.setCursorPos(xW, xH)
      term.write(deText)
    end
  end
end
 
local function drawHeader()
  local title = runState == "Help" and "gtRemote  " .. gtRver or "gtRemote"
  drawElement(1, 1, termX, 1, white, blue, title) -- title bar
  if runState == "List" or runState == "goPage" then
    drawElement(1, 1, 3, 1, nil, nil, "[ ]")
    drawElement(2, 1, 1, 1, fuelFilter and gray or green, nil, "F")
    drawElement(termX - 2, 1, 3, 1, white, nil, "[ ]")
    drawElement(termX - 1, 1, 1, 1, red, nil, "X")
    local word1 = string.rep(" ", math.floor(termX / 4 - 2)) .. "All ON" .. string.rep(" ", math.floor(termX / 4 - 2))
    local word2 = string.rep(" ", math.ceil(termX / 4 - 2)) .. "All OFF" .. string.rep(" ", math.ceil(termX / 4 - 2))
    drawElement(1, 2, 1, 1, green, gray, word1)
    drawElement(termX / 2, 2, 1, 1, red, nil, word2)
  elseif runState == "Remote" or runState == "Inventory" or runState == "Help" then
    drawElement(1, 2, termX, 1, red, gray, "Close")
  end
end
 
local function drawColorList(gRating)
  local tColors = {
                    [1] = { text = "Blue", color = blue, gRating = "B" },
                    [2] = { text = "Sky", color = sky, gRating = "S" },
                    [3] = { text = "Brown", color = brown, gRating = "N" },
                    [4] = { text = "Purple", color = purple, gRating = "P" },
                    [5] = { text = "Green", color = green, gRating = "G" },
                    [6] = { text = "Orange", color = orange, gRating = "O" },
                    [7] = { text = "Red", color = red, gRating = "R" },
                    [8] = { text = "Silver", color = silver, gRating = "I" },
                  }
  local longest = 0                      --
  for k, v in ipairs(tColors) do         --
    longest = math.max(#v.text, longest) -- find longest color name for menu width
  end                                    --
  local posY = 4                         -- cursor Y
  local gRatingCol
  for i = 1, #tColors, 1 do
    local thisEntry = tColors[i]
    drawElement(7, posY, 1, 1, white, thisEntry.color, " ") -- color pips
    term.setBackgroundColor(gray)        -- menu b/g
    if gRating == thisEntry.gRating then --
      gRatingCol = thisEntry.color       -- Selected text color
      term.setTextColor(gRatingCol)      --
    else
      term.setTextColor(silver)          -- Unselected text color
    end
    term.write(" "..thisEntry.text..string.rep(" ", longest - #thisEntry.text).." ")
    posY = posY + 1                      -- increment cursor Y pos
  end
  local xColorLine = 7 + longest + 3     -- draw selected color line
  paintutils.drawLine(xColorLine, 4, xColorLine, posY-1, gRatingCol) --
end
 
local function drawPLBR()
  if tDirection == "Up" then
    if allTurtles[thisTurtle].up then
      drawElement(7, 8, 2, 1, white, red, "PL")   -- Place/Break
      drawElement(7, 9, 2, 1, nil, nil, "BR")
      sleep(0.01)
      drawElement(7, 8, 2, 1, black, gray, "PL")  -- Place/Break
      drawElement(7, 9, 2, 1, nil, red, "BR")
    else
      drawElement(7, 8, 2, 1, white, green, "PL") -- Place/Break
      drawElement(7, 9, 2, 1, nil, nil, "BR")
      sleep(0.01)
      drawElement(7, 8, 2, 1, black, nil, "PL")   -- Place/Break
      drawElement(7, 9, 2, 1, nil, gray, "BR")
    end
  elseif tDirection == "Down" then
    if allTurtles[thisTurtle].down then
      drawElement(7, 8, 2, 1, white, red, "PL")   -- Place/Break
      drawElement(7, 9, 2, 1, nil, nil, "BR")
      sleep(0.01)
      drawElement(7, 8, 2, 1, black, gray, "PL")  -- Place/Break
      drawElement(7, 9, 2, 1, nil, red, "BR")
    else
      drawElement(7, 8, 2, 1, white, green, "PL") -- Place/Break
      drawElement(7, 9, 2, 1, nil, nil, "BR")
      sleep(0.01)
      drawElement(7, 8, 2, 1, black, nil, "PL")   -- Place/Break
      drawElement(7, 9, 2, 1, nil, gray, "BR")
    end
  elseif tDirection == "Forward" then
    if allTurtles[thisTurtle].forward then
      drawElement(7, 8, 2, 1, white, red, "PL")   -- Place/Break
      drawElement(7, 9, 2, 1, nil, nil, "BR")
      sleep(0.01)
      drawElement(7, 8, 2, 1, black, gray, "PL")  -- Place/Break
      drawElement(7, 9, 2, 1, nil, red, "BR")
    else
      drawElement(7, 8, 2, 1, white, green, "PL") -- Place/Break
      drawElement(7, 9, 2, 1, nil, nil, "BR")
      sleep(0.01)
      drawElement(7, 8, 2, 1, black, nil, "PL")   -- Place/Break
      drawElement(7, 9, 2, 1, nil, gray, "BR")
    end
  end
end
 
local function fuelGauge()
  if not allTurtles[thisTurtle].fuelPercent then
    allTurtles[thisTurtle].fuelPercent = 0
  end
  local fuelColor
  if allTurtles[thisTurtle].fuelPercent > 50 then
    fuelColor = green
  elseif allTurtles[thisTurtle].fuelPercent < 51 and allTurtles[thisTurtle].fuelPercent > 25 then
    fuelColor = orange
  elseif allTurtles[thisTurtle].fuelPercent < 26 then
    fuelColor = red
  end
  return fuelColor
end
 
local function staticTurtleInventory()
  drawHeader()
  drawElement(2, 4, termX-2, 1, silver, black, allTurtles[thisTurtle].name .. "'s Inventory")
  drawElement(2, 6, 13, 9, white, gray, "") -- Inventory 'box'
  drawElement(2, 16, 1, 1, gray, black, "Selected Slot:")
  drawElement(2, 17, 1, 1, nil, nil, "Direction:")
  drawElement(16, 7, 9, 1, black, yellow, " Refuel")
  drawElement(16, 9, 9, 1, nil, green, "Place")
  drawElement(16, 11, 9, 1, nil, red, "Break")
  drawElement(16, 13, 9, 1, nil, silver, "Equip")
  drawElement((termX / 2) - 9, termY - 1, 1, 1, white, brown, " Refresh Inventory ")
end
 
turtleInventory = function()
  tmpState = "Remote"
  local i = 1           -- inventory slot
  for y = 7, 13, 2 do   -- y position
    for x = 3, 12, 3 do -- x position
      local tiColor = white                    --
      local biColor = black                    -- set text and bg color
      if i == allTurtles[thisTurtle].slot then --
        tiColor = black                        -- set text and bg color for selected slot
        biColor = silver                       --
      end
      drawElement(x, y, 2, 1, tiColor, biColor, tostring(allTurtles[thisTurtle].inv[i])) -- write inventory count
      i = i + 1         -- increment inventory slot
    end
  end
  drawElement(17, 16, 1, 1, sky, black, tostring(allTurtles[thisTurtle].slot) .. " ")
  drawElement(13, 17, 1, 1, silver, nil, tDirection .. "     ")
end
 
local function directionButtons()
  if not allTurtles[thisTurtle].forward or not allTurtles[thisTurtle].dirCheck then
    drawElement(5, 8, 2, 1, black, white, "/\\")  -- Forward
  else
    drawElement(5, 8, 2, 1, red, white, "/\\")    -- Forward
  end
  drawElement(5, 9, 2, 1, nil, nil, "")
  drawElement(5, 12, 2, 2, black, nil, "\\/")     -- Back
  drawElement(3, 10, 2, 1, nil, nil, "/ ")        -- Left
  drawElement(3, 11, 2, 1, nil, nil, "\\ ")       --
  drawElement(7, 10, 2, 1, nil, nil, " \\")       -- Right
  drawElement(7, 11, 2, 1, nil, nil, " /")        --
  drawElement(5, 10, 2, 1, white, black, "..")    -- Center
  drawElement(5, 11, 2, 1, nil, nil, "..")        --
  if not allTurtles[thisTurtle].up or not allTurtles[thisTurtle].dirCheck then
    drawElement(3, 8, 2, 1, black, gray, "/\\")   -- Up
  else
    drawElement(3, 8, 2, 1, red, gray, "/\\")     -- Up
  end
  drawElement(3, 9, 2, 1, nil, nil, "")
  if not allTurtles[thisTurtle].down or not allTurtles[thisTurtle].dirCheck then
    drawElement(3, 12, 2, 2, black, gray, "\\/")  -- Down
  else
    drawElement(3, 12, 2, 2, red, gray, "\\/")    -- Down
  end
  if allTurtles[thisTurtle].dirCheck then
    if allTurtles[thisTurtle].forward then
      drawElement(7, 8, 2, 1, black, gray, "PL")  -- Place/Break
      drawElement(7, 9, 2, 1, nil, red, "BR")
    else
      drawElement(7, 8, 2, 1, black, green, "PL") -- Place/Break
      drawElement(7, 9, 2, 1, nil, gray, "BR")
    end
  else
    drawElement(7, 8, 2, 1, black, gray, "PL")    -- Place/Break
    drawElement(7, 9, 2, 1, nil, nil, "BR")
  end
  if allTurtles[thisTurtle].dirCheck then
    drawElement(7, 12, 2, 1, black, gray, "OB")   -- Obstacle check
    drawElement(7, 13, 2, 1, nil, green, "CK")
  else
    drawElement(7, 12, 2, 1, black, red, "OB")    -- Obstacle check
    drawElement(7, 13, 2, 1, nil, gray, "CK")
  end
end
 
local function turtleControlScreen(dataBlock)
  thisTurtle = dataBlock
  runState = "Remote"
  drawHeader()
  -- Display data for viewing/editing
  term.setBackgroundColor(black)
  if tonumber(thisTurtle) <= #allTurtles then
    local teColor = assignMasterColor(thisTurtle)
    if teColor ~= nil then
      drawElement(2, 4, 1, 1, teColor, black, allTurtles[thisTurtle].name) -- Name
      local thisCC = tostring(allTurtles[thisTurtle].cc) -- cc#
      drawElement(12, 4, 1, 1, gray, black, "cc#")
      drawElement(16, 4, 1, 1, white, nil, thisCC)
      drawElement(2, 6, 1, 1, silver, nil, allTurtles[thisTurtle].note)  -- Short description
      directionButtons()                                 -- Movement Controls
      drawElement(12, 8, 1, 1, red, black, "Redstone ")  -- Redstone Output
      if allTurtles[thisTurtle].redstone then
        drawElement(22, 8, "ON")
      else
        drawElement(22, 8, "OFF")
      end
      drawElement(12, 10, 1, 1, gray, black, "Fuel ")    -- Fuel Gauge
      term.setTextColor(fuelGauge())
      if allTurtles[thisTurtle].fuelPercent == 101 then
        term.write("Unlimited")
      else
        term.write(tostring(allTurtles[thisTurtle].fuelPercent) .. "%  ")
      end
      if showFuel then
        drawElement(12, 11, 1, 1, gray, nil, "Units ")
        term.write(tostring(allTurtles[thisTurtle].fuelAmount) .. "   ")
      else
        drawElement(12, 11, 1, 1, gray, nil, "Coal ")
        term.write(tostring(allTurtles[thisTurtle].coal) .. "   ")
      end
      drawElement(12, 13, 11, 1, white, brown, "Inventory") -- Inventory button
      drawElement(16, 15, 9, 1, black, gray, "Refresh")     -- Turtle location (Refresh GPS fix button)
      drawElement(16, 16, 9, 1, nil, nil, "GPS Fix")
      if allTurtles[thisTurtle].loc.x ~= "No GPS Fix" then  -- pgps export (export to pocketgps button)
        drawElement(16, 17, 9, 1, black, silver, "Export")
        drawElement(16, 18, 9, 1, nil, nil, "to pgps")
      end
      drawElement(2, 15, 1, 1, silver, black, "Last Fix:")  -- Turtle location (x/y/z)
      drawElement(2, 16, 1, 1, nil, nil, "x:")
      drawElement(2, 17, 1, 1, nil, nil, "y:")
      drawElement(2, 18, 1, 1, nil, nil, "z:")
      drawElement(5, 16, 1, 1, brown, nil, allTurtles[thisTurtle].loc.x .. string.rep(" ", 11-#tostring(allTurtles[thisTurtle].loc.x)))
      drawElement(5, 17, 1, 1, nil, nil, allTurtles[thisTurtle].loc.y .. string.rep(" ", 11-#tostring(allTurtles[thisTurtle].loc.y)))
      drawElement(5, 18, 1, 1, nil, nil, allTurtles[thisTurtle].loc.z .. string.rep(" ", 11-#tostring(allTurtles[thisTurtle].loc.z)))
    end
  end
end
 
local function drawNaviUI()
  local pNum = tostring(pageNum)
  if pageNum < 100 then pNum = "0" .. pNum end -- Add a "0" before double digit page numbers
  if pageNum < 10 then pNum = "0" .. pNum end  -- Add another "0" before single digit page numbers
  drawElement((termX / 2) - 10, termY, 7, 1, gray, black, pageNum > 1 and "<< BACK" or "       ")
  drawElement((termX / 2) + 4, termY, 7, 1, nil, nil, pageNum < numPages and "NEXT >>" or "       ")
  drawElement((termX / 2) - (math.floor(pNum:len() / 2)), termY, 3, 1, silver, nil, pNum) -- Page Number
end
 
local function drawHelpUI()
  drawElement(1, 3, termX, termY, black, white, "")
  drawHeader()
  if tmpState == "List" then
    drawElement(2, 4, termX-1, 1, black, white, "Left click a turtle to")
    drawElement(2, 5, termX-1, 1, nil, nil, "control and manage it")
    drawElement(2, 7, termX-1, 1, nil, nil, "Middle click a turtle to")
    drawElement(2, 8, termX-1, 1, nil, nil, "lock or unlock")
    drawElement(2, 11, termX-1, 1, nil, nil, "'All ON / All OFF'")
    drawElement(2, 12, termX-1, 1, nil, nil, "controls redstone output")
    drawElement(2, 13, termX-1, 1, nil, nil, "on turtles in range")
    drawElement(2, 15, termX-1, 1, nil, nil, "[F] = Fuel Filter")
    drawElement(2, 16, termX-1, 1, nil, nil, "Filters turtles based")
    drawElement(2, 17, termX-1, 1, nil, nil, "on fueled status")
  elseif tmpState == "Remote" then
    drawElement(2, 4, termX-1, 1, black, white, "Click arrows to drive")
    drawElement(2, 5, termX-1, 1, nil, nil, "or use [W, A, S, D, Q, E]")
    drawElement(2, 7, termX-1, 1, nil, nil, "PL/BR[P] = Place/Break   ")
    drawElement(2, 8, termX-1, 1, nil, nil, "OB/CK[O] = Obstacle check")
    drawElement(2, 10, termX-1, 1, nil, nil, "Left click name or note")
    drawElement(2, 11, termX-1, 1, nil, nil, "to edit")
    drawElement(2, 12, termX-1, 1, nil, nil, "Right click name to")
    drawElement(2, 13, termX-1, 1, nil, nil, "change color")
    drawElement(2, 15, termX-1, 1, nil, nil, "Redstone [R] controls")
    drawElement(2, 16, termX-1, 1, nil, nil, "RS output on the front")
    drawElement(2, 18, termX-1, 1, nil, nil, "'Export to pgps' adds")
    drawElement(2, 19, termX-1, 1, nil, nil, "turtle to pgps .places")
  elseif tmpState == "Inventory" then
    drawElement(2, 4, termX-1, 1, black, white, "Click inventory slots")
    drawElement(2, 5, termX-1, 1, nil, nil, "to select for action")
    drawElement(2, 7, termX-1, 1, nil, nil, "Click action button")
    drawElement(2, 8, termX-1, 1, nil, nil, "to carry out action")
    drawElement(2, 10, termX-1, 1, nil, nil, "Right click 'Place' to")
    drawElement(2, 11, termX-1, 1, nil, nil, "engrave a sign")
    drawElement(2, 13, termX-1, 1, nil, nil, "Right click 'Break' to")
    drawElement(2, 14, termX-1, 1, nil, nil, "attack")
    drawElement(2, 16, termX-1, 1, nil, nil, "Left click the displayed")
    drawElement(2, 17, termX-1, 1, nil, nil, "direction to change the")
    drawElement(2, 18, termX-1, 1, nil, nil, "direction of action")
  end
end
 
local function drawMainUI() -- Turtle 'Address Book'
  local xPos, yPos = 1, 4
  local magicNumber = ((pageNum - 1) * 23) + pageNum
  for i = magicNumber, #filteredTurtles do
    term.setCursorPos(xPos, yPos)
    if filteredTurtles[i] then
      if not filteredTurtles[i].lockState then
        if filteredTurtles[i].fuelState then
          term.setBackgroundColor(assignColor(i))
          term.setTextColor(white)
        else
          term.setBackgroundColor(black)
          term.setTextColor(assignColor(i))
        end
      else
        term.setBackgroundColor(gray)
        term.setTextColor(silver)
      end
      if i > pageNum * 24 then
        break
      else
        term.write(string.rep(" ", math.floor((8 - #filteredTurtles[i].name) / 2)) .. filteredTurtles[i].name:sub(1, 8) .. string.rep(" ", math.ceil((8 - #filteredTurtles[i].name) / 2))) -- Dial
      end
    end
    yPos = yPos + 2
    if yPos > 19 then yPos = 4 xPos = xPos + 9 end
    if xPos > termX - 7 then break end
  end
  term.setBackgroundColor(black)
end
 
drawCLI = function() -- Client Interface 'decider'
  if not inputting then
    local states = {
                     List = function() drawMainUI() drawNaviUI() end,
                     Remote = function() turtleControlScreen(thisTurtle) end,
                     Inventory = function() staticTurtleInventory() turtleInventory() end,
                   }
    drawHeader()
    for state, func in pairs(states) do
      if runState == tostring(state) then
        return func()
      end
    end
  end
end
 
local function readInput(cX, cY, cO, bG) -- cursor X, Y, text color, bg color
  local word = ""
  local curX, curY = cX, cY
  inputting = true
  if not bG then bG = black end
  term.setTextColor(cO)
  term.setCursorBlink(true)
  term.setCursorPos(curX, curY)
  while true do
    local kEvent = { os.pullEvent() }
    if kEvent[1] == "key" then
      if kEvent[2] == keys.backspace then
        if curX > cX then
          curX = curX - 1
          word = word:sub(1, #word-1)
        end
        drawElement(curX, curY, 1, 1, cO, bG, " ")
      elseif kEvent[2] == keys.enter then
        term.setCursorBlink(false)
        inputting = false
        return word
      end
    elseif kEvent[1] == "char" then
      drawElement(curX, curY, 1, 1, cO, bG, kEvent[2])
          word = word .. kEvent[2]
      curX = curX + 1
    elseif kEvent[1] == "mouse_click" then
      local mX, mY = kEvent[3], kEvent[4]
      if mY ~= curY or mX < curX - #word or (mX > curX + 3 or mX > curX - #word + 13) then
        term.setCursorBlink(false)
        inputting = false
        return word
      end
    elseif kEvent[1] == "timer" and kEvent[2] == pollTimer then
      --term.setCursorPos(cX, cY)
      --term.write(word)
      timerDelay = true
    end
    term.setCursorPos(curX, curY)
  end
end
 
local function editEntry()
  if tEdit == "name" then
    while true do
      local newName = tostring(readInput(2, 4, yellow))
      if newName ~= "" and newName ~= "nil" then
        allTurtles[thisTurtle].name = newName:sub(1, 8) -- We set this so the screen updates immediately and so we have the 8 character name to send
        netSend(allTurtles[thisTurtle].cc, "name", allTurtles[thisTurtle].name)
        local gColor = assignMasterColor(thisTurtle)
        local gDev = allTurtles[thisTurtle].name .. string.rep(" ", 8-#allTurtles[thisTurtle].name)
        drawHeader()
        drawElement(2, 4, 8, 1, nil, black, "")
        drawElement(2, 4, #gDev, 1, gColor, nil, gDev)
        runState = "Remote"
        return newName
      else
        local gColor = assignMasterColor(thisTurtle)
        local gDev = allTurtles[thisTurtle].name .. string.rep(" ", 8-#allTurtles[thisTurtle].name)
        drawElement(2, 4, 8, 1, nil, black, "")
        drawElement(2, 4, #gDev, 1, gColor, nil, gDev)
        runState = "Remote"
        return
      end
    end
  elseif tEdit == "note" then
    while true do
      local newNote = tostring(readInput(2, 6, white))
      if newNote ~= "" and newNote ~= "nil" then
        allTurtles[thisTurtle].note = newNote -- We set this so the screen updates immediately
        netSend(allTurtles[thisTurtle].cc, "note", newNote)
        drawHeader()
        drawElement(2, 6, termX, 2, nil, black, "")
        drawElement(2, 6, #allTurtles[thisTurtle].note, 1, silver, nil, allTurtles[thisTurtle].note)
        runState = "Remote"
        return newNote
      else
        drawElement(2, 6, termX, 2, nil, black, "")
        drawElement(2, 6, #allTurtles[thisTurtle].note, 1, silver, nil, allTurtles[thisTurtle].note)
        runState = "Remote"
        return
      end
    end
  end
end
 
local function getSignText()
  drawElement(termX / 2 - 8, termY / 2 - 1, 17, 1, black, silver, "Engrave")
  drawElement(termX / 2 - 8, termY / 2, 17, 2, nil, nil, "")
  drawElement(termX / 2 - 7, termY / 2, 15, 1, white, black, "")
  local newText = readInput((termX / 2) - 7, termY / 2, lime)
  if newText == "" or newText == "nil" then
    runState = "Inventory"
    drawElement(termX / 2 - 8, termY / 2 - 1, 17, 3, white, nil, "")
    staticTurtleInventory()
    turtleInventory()
    return
  else
    netSend(allTurtles[thisTurtle].cc, "put", newText)
    runState = "Inventory"
    drawElement(termX / 2 - 8, termY / 2 - 1, 17, 3, white, nil, "")
    drawCLI()
    return
  end
end
 
local function enterPassword()
  drawElement((termX / 2) - 7, 8, 15, 1, white, gray, "   Password:   ")
  drawElement((termX / 2) - 7, 9, 15, 2, nil, nil, "")
  drawElement((termX / 2) - 6, 9, 13, 1, nil, black, "") -- input area bg
  local pass = readInput(termX / 2 - 6, 9, lime)
  drawElement((termX / 2) - 7, 8, 15, 3, white, nil, "")
  if not allTurtles[thisTurtle].lockState then
    netSend(allTurtles[thisTurtle].cc, "lock", pass)
  else
    netSend(allTurtles[thisTurtle].cc, "unlock", pass)
  end
  runState = "List"
end
 
local function colorPicker()
  local colorCodes = { "B", "S", "N", "P", "G", "O", "R", "I", }
  while true do
    local newColor = { os.pullEvent("mouse_click") }
    if newColor[3] > 6 and newColor[3] < 17 then
      for colorChoice = 4, 11, 1 do
        if newColor[4] == colorChoice then
          for i = 1, #colorCodes, 1 do
            if (colorChoice - 3) == i then
              netSend(allTurtles[thisTurtle].cc, "color", colorCodes[i])
              break
            end
          end
        end
      end
      break
    else
      break
    end
  end
  runState = "Remote"
  drawElement(2, 2, termX, termY, nil, black, "")
  turtleControlScreen(thisTurtle)
end
 
local function shellCommand()
  drawElement((termX / 2) - 7, 8, 15, 1, white, gray, "   Command:    ")
  drawElement((termX / 2) - 7, 9, 15, 2, nil, nil, "")
  drawElement((termX / 2) - 6, 9, 13, 1, nil, black, "") -- input area bg
  local sCommand = readInput((termX / 2) - 6, 9, lime)
  drawElement((termX / 2) - 7, 8, 15, 3, nil, nil, "")
  if sCommand ~= nil and sCommand ~= "nil" and sCommand ~= "" then
    netSend(allTurtles[thisTurtle].cc, "sCmd", sCommand)
  end
  runState = "Remote"
  turtleControlScreen(thisTurtle)
end
 
local function goToPage()
  drawElement((termX / 2) - 7, 8, 15, 1, white, gray, "  Go To Page:  ")
  drawElement((termX / 2) - 7, 9, 15, 2, nil, nil, "")
  drawElement((termX / 2) - 6, 9, 13, 1, nil, black, "") -- input area bg
  local newPage = tonumber(readInput((termX / 2) - 6, 9, lime))
  drawElement((termX / 2) - 7, 8, 15, 3, nil, nil, "")
  pageNum = newPage or pageNum
  pageNum = math.max(1, pageNum)
  pageNum = math.min(pageNum, numPages)
  if pageNum == numPages and numPages > 1 then
    drawElement(1, 4, termX, termY, nil, nil, "")
  end
  runState = "List"
  drawCLI()
end
 
local function keyClick()
  --while true do
    local _, inputKey = os.pullEvent("key")
    if runState == "List" then
      if inputKey == 33 then                          -- F / Fuel Filter
        fuelFilter = not fuelFilter
        filterTurtleList()
        drawElement(1, 3, termX, termY, nil, black, "")
        drawCLI()
        return
      elseif inputKey == 59 then                      -- F1 / Help
        if runState ~= "Help" then
          tmpState = runState
          runState = "Help"
          drawHelpUI()
          return
        end
      end
    elseif runState == "Inventory" then               -- F1 / Help
      if inputKey == 59 then
        if runState ~= "Help" then
          tmpState = runState
          runState = "Help"
          drawHelpUI()
          return
        end
      end
    elseif runState == "Remote" then
      if inputKey == 59 then                          -- F1 / Help
        if runState ~= "Help" then
          tmpState = runState
          runState = "Help"
          drawHelpUI()
          return
        end
      elseif inputKey == 16 then                      -- Q (down)
        drawElement(3, 12, 2, 2, black, white, "\\/") -- Down
        netSend(allTurtles[thisTurtle].cc, "move", "down")
        sleep(0.01)
        drawElement(3, 12, 2, 2, nil, gray, "\\/")    -- Down
        return
      elseif inputKey == 17 then                      -- W (forward)
        drawElement(5, 8, 2, 1, white, gray, "/\\")   -- Forward
        drawElement(5, 9, 2, 1, nil, nil, "")
        netSend(allTurtles[thisTurtle].cc, "move", "forward")
        sleep(0.01)
        drawElement(5, 8, 2, 1, black, white, "/\\")  -- Forward
        drawElement(5, 9, 2, 1, nil, nil, "")
        return
      elseif inputKey == 18 then                      -- E (up)
        drawElement(3, 8, 2, 1, black, white, "/\\")  -- Up
        drawElement(3, 9, 2, 1, nil, nil, "")
        netSend(allTurtles[thisTurtle].cc, "move", "up")
        sleep(0.01)
        drawElement(3, 8, 2, 1, black, gray, "/\\")   -- Up
        drawElement(3, 9, 2, 1, nil, nil, "")
        return
      elseif inputKey == 19 then                      -- R (redstone)
        if allTurtles[thisTurtle].redstone then
          netSend(allTurtles[thisTurtle].cc, "rds", false)
        else
          netSend(allTurtles[thisTurtle].cc, "rds", true)
        end
        sleep(0.01)
        turtleControlScreen(thisTurtle)
        return
      elseif inputKey == 25 then                      -- P (Place/Break)
        if allTurtles[thisTurtle].dirCheck then
          drawPLBR()
        else
          drawElement(7, 8, 2, 1, black, white, "PL") -- Place/Break
          drawElement(7, 9, 2, 1, nil, nil, "BR")
          sleep(0.01)
          drawElement(7, 8, 2, 1, nil, gray, "PL")    -- Place/Break
          drawElement(7, 9, 2, 1, nil, nil, "BR")
        end
        if tDirection == "Up" then
          if allTurtles[thisTurtle].up then
            netSend(allTurtles[thisTurtle].cc, "dig", tDirection)
          else
            netSend(allTurtles[thisTurtle].cc, "put", tDirection)
          end
        elseif tDirection == "Down" then
          if allTurtles[thisTurtle].down then
            netSend(allTurtles[thisTurtle].cc, "dig", tDirection)
          else
            netSend(allTurtles[thisTurtle].cc, "put", tDirection)
          end
        elseif tDirection == "Forward" then
          if allTurtles[thisTurtle].forward then
            netSend(allTurtles[thisTurtle].cc, "dig", tDirection)
          else
            netSend(allTurtles[thisTurtle].cc, "put", tDirection)
          end
        end
        return
      elseif inputKey == 30 then                      -- A (left)
        drawElement(3, 10, 2, 1, white, gray, "/ ")   -- Left
        drawElement(3, 11, 2, 1, nil, nil, "\\ ")     --
        netSend(allTurtles[thisTurtle].cc, "move", "left")
        sleep(0.01)
        drawElement(3, 10, 2, 1, black, white, "/ ")  -- Left
        drawElement(3, 11, 2, 1, nil, nil, "\\ ")     --
        return
      elseif inputKey == 31 then                      -- S (back)
        drawElement(5, 12, 2, 2, white, gray, "\\/")  -- Back
        netSend(allTurtles[thisTurtle].cc, "move", "back")
        sleep(0.01)
        drawElement(5, 12, 2, 2, black, white, "\\/") -- Back
        return
      elseif inputKey == 32 then                      -- D (right)
        drawElement(7, 10, 2, 1, white, gray, " \\")  -- Right
        drawElement(7, 11, 2, 1, nil, nil, " /")      --
        netSend(allTurtles[thisTurtle].cc, "move", "right")
        sleep(0.01)
        drawElement(7, 10, 2, 1, black, white, " \\") -- Right
        drawElement(7, 11, 2, 1, nil, nil, " /")      --
        return
      elseif inputKey == 24 then                      -- O (Obstacle check)
        allTurtles[thisTurtle].dirCheck = not allTurtles[thisTurtle].dirCheck
        netSend(allTurtles[thisTurtle].cc, "dcToggle", allTurtles[thisTurtle].dirCheck)
        return
      end
    elseif runState == "Help" then
      if inputKey == 59 then
        drawElement(1, 2, termX, termY, nil, black, "")
        runState = tmpState
        drawCLI()
        return
      end
    end
  --end
end
 
local function mClick()
  --while true do
    local _, mButton, mcX, mcY = os.pullEvent("mouse_click")
    if runState == "Help" then
      if mcY == 2 then
        drawElement(1, 2, termX, termY, nil, black, "")
        runState = tmpState
        if runState == "List" or runState == "Remote" or runState == "Inventory" then drawCLI() end
        return
      end
    elseif runState == "Remote" then
       -- Exit Remote/Edit Screen
      if mcY == 2 then
        if postponedSort then
          postponedSort = false
          sortTurtleList()
        end
        drawElement(2, 2, termX, termY, nil, black, "")
        runState = "List"
        drawCLI()
        return
      elseif mcY == 4 then
        if mcX > 1 and mcX < 10 then
         -- Edit Turtle Name
          if mButton == 1 then
            drawElement(2, 4, 1, 1, gray, black, allTurtles[thisTurtle].name)
            runState = "Edit"
            tEdit = "name"
           -- Change color assignment
          elseif mButton == 2 then
            drawColorList(allTurtles[thisTurtle].color)
            runState = "color"
          end
        end
        return
       -- Edit Turtle Note
      elseif mcY == 6 and mButton == 1 then
        if mcX > 1 then
          drawElement(2, 6, 1, 1, gray, black, allTurtles[thisTurtle].note)
          term.setBackgroundColor(black)
          runState = "Edit"
          tEdit = "note"
        end
        return
       -- Movement / Actions
      elseif mcY == 8 and mButton == 1 then
        if mcX > 2 and mcX < 5 then                     -- UP
          drawElement(3, 8, 2, 1, black, white, "/\\")  -- Up
          drawElement(3, 9, 2, 1, nil, nil, "")
          netSend(allTurtles[thisTurtle].cc, "move", "up")
          sleep(0.01)
          drawElement(3, 8, 2, 1, black, gray, "/\\")   -- Up
          drawElement(3, 9, 2, 1, nil, nil, "")
          return
        elseif mcX > 4 and mcX < 7 then                 -- Forward
          drawElement(5, 8, 2, 1, white, gray, "/\\")   -- Forward
          drawElement(5, 9, 2, 1, nil, nil, "")
          netSend(allTurtles[thisTurtle].cc, "move", "forward")
          sleep(0.01)
          drawElement(5, 8, 2, 1, black, white, "/\\")  -- Forward
          drawElement(5, 9, 2, 1, nil, nil, "")
          return
        elseif mcX > 6 and mcX < 9 then                 -- Place/Break
          if allTurtles[thisTurtle].dirCheck then
            drawPLBR()
          else
            drawElement(7, 8, 2, 1, black, white, "PL") -- Place/Break
            drawElement(7, 9, 2, 1, nil, nil, "BR")
            sleep(0.01)
            drawElement(7, 8, 2, 1, black, gray, "PL")  -- Place/Break
            drawElement(7, 9, 2, 1, nil, nil, "BR")
          end
          if tDirection == "Up" then
            if allTurtles[thisTurtle].up then
              netSend(allTurtles[thisTurtle].cc, "dig", tDirection)
            else
              netSend(allTurtles[thisTurtle].cc, "put", tDirection)
            end
          elseif tDirection == "Down" then
            if allTurtles[thisTurtle].down then
              netSend(allTurtles[thisTurtle].cc, "dig", tDirection)
            else
              netSend(allTurtles[thisTurtle].cc, "put", tDirection)
            end
          elseif tDirection == "Forward" then
            if allTurtles[thisTurtle].forward then
              netSend(allTurtles[thisTurtle].cc, "dig", tDirection)
            else
              netSend(allTurtles[thisTurtle].cc, "put", tDirection)
            end
          end
          return
         -- Redstone output
        elseif mcX > 21 and mcX < 26 then
          if allTurtles[thisTurtle].redstone then
            netSend(allTurtles[thisTurtle].cc, "rds", false)
            sleep(0.01)
            turtleControlScreen(thisTurtle)
          else
            netSend(allTurtles[thisTurtle].cc, "rds", true)
            sleep(0.01)
            turtleControlScreen(thisTurtle)
          end
        end
        return
      elseif mcY == 9 and mButton == 1 then
        if mcX > 2 and mcX < 5 then                       -- UP
          drawElement(3, 8, 2, 1, black, white, "/\\")    -- Up
          drawElement(3, 9, 2, 1, nil, nil, "")
          netSend(allTurtles[thisTurtle].cc, "move", "up")
          sleep(0.01)
          drawElement(3, 8, 2, 1, black, gray, "/\\")     -- Up
          drawElement(3, 9, 2, 1, nil, nil, "")
        elseif mcX > 4 and mcX < 7 then                   -- Forward
          drawElement(5, 8, 2, 1, white, gray, "/\\")     -- Forward
          drawElement(5, 9, 2, 1, nil, nil, "")
          netSend(allTurtles[thisTurtle].cc, "move", "forward")
          sleep(0.01)
          drawElement(5, 8, 2, 1, black, white, "/\\")    -- Forward
          drawElement(5, 9, 2, 1, nil, nil, "")
        elseif mcX > 6 and mcX < 9 then                   -- Tunnel
          if allTurtles[thisTurtle].dirCheck then
            if allTurtles[thisTurtle].forward then
              drawElement(7, 8, 2, 1, black, red, "PL")   -- Place/Break
              drawElement(7, 9, 2, 1, nil, nil, "BR")
              sleep(0.01)
              drawElement(7, 8, 2, 1, nil, gray, "PL")    -- Place/Break
              drawElement(7, 9, 2, 1, nil, red, "BR")
            else
              drawElement(7, 8, 2, 1, black, green, "PL") -- Place/Break
              drawElement(7, 9, 2, 1, nil, nil, "BR")
              sleep(0.01)
              drawElement(7, 8, 2, 1, nil, nil, "PL")     -- Place/Break
              drawElement(7, 9, 2, 1, nil, gray, "BR")
            end
            if allTurtles[thisTurtle].forward then
              netSend(allTurtles[thisTurtle].cc, "dig", "forward")
            else
              netSend(allTurtles[thisTurtle].cc, "put", "forward")
            end
          else
            drawElement(7, 8, 2, 1, black, white, "PL")   -- Place/Break
            drawElement(7, 9, 2, 1, nil, nil, "BR")
            sleep(0.01)
            drawElement(7, 8, 2, 1, nil, gray, "PL")      -- Place/Break
            drawElement(7, 9, 2, 1, nil, nil, "BR")
            if tDirection == "Up" then
              if allTurtles[thisTurtle].up then
                netSend(allTurtles[thisTurtle].cc, "dig", tDirection)
              else
                netSend(allTurtles[thisTurtle].cc, "put", tDirection)
              end
            elseif tDirection == "Down" then
              if allTurtles[thisTurtle].down then
                netSend(allTurtles[thisTurtle].cc, "dig", tDirection)
              else
                netSend(allTurtles[thisTurtle].cc, "put", tDirection)
              end
            elseif tDirection == "Forward" then
              if allTurtles[thisTurtle].forward then
                netSend(allTurtles[thisTurtle].cc, "dig", tDirection)
              else
                netSend(allTurtles[thisTurtle].cc, "put", tDirection)
              end
            end
          end
        end
        return
      elseif mcY == 10 and mButton == 1 then
        if mcX > 2 and mcX < 5 then                     -- Left
          drawElement(3, 10, 2, 1, white, gray, "/ ")   -- Left
          drawElement(3, 11, 2, 1, nil, nil, "\\ ")     --
          netSend(allTurtles[thisTurtle].cc, "move", "left")
          sleep(0.01)
          drawElement(3, 10, 2, 1, black, white, "/ ")  -- Left
          drawElement(3, 11, 2, 1, nil, nil, "\\ ")     --
        elseif mcX > 4 and mcX < 7 then                 -- Center
          runState = "shellCmd"
        elseif mcX > 6 and mcX < 9 then                 -- Right
          drawElement(7, 10, 2, 1, white, gray, " \\")  -- Right
          drawElement(7, 11, 2, 1, nil, nil, " /")      --
          netSend(allTurtles[thisTurtle].cc, "move", "right")
          sleep(0.01)
          drawElement(7, 10, 2, 1, black, white, " \\") -- Right
          drawElement(7, 11, 2, 1, nil, nil, " /")      --
        end
        return
      elseif mcY == 11 and mButton == 1 then
        if mcX > 2 and mcX < 5 then                     -- Left
          drawElement(3, 10, 2, 1, white, gray, "/ ")   -- Left
          drawElement(3, 11, 2, 1, nil, nil, "\\ ")     --
          netSend(allTurtles[thisTurtle].cc, "move", "left")
          sleep(0.01)
          drawElement(3, 10, 2, 1, black, white, "/ ")  -- Left
          drawElement(3, 11, 2, 1, nil, nil, "\\ ")     --
        elseif mcX > 4 and mcX < 7 then                 -- Center
          runState = "shellCmd"
        elseif mcX > 6 and mcX < 9 then                 -- Right
          drawElement(7, 10, 2, 1, white, gray, " \\")  -- Right
          drawElement(7, 11, 2, 1, nil, nil, " /")      --
          netSend(allTurtles[thisTurtle].cc, "move", "right")
          sleep(0.01)
          drawElement(7, 10, 2, 1, black, white, " \\") -- Right
          drawElement(7, 11, 2, 1, nil, nil, " /")      --
          -- Fuel/Coal
        elseif mcX > 11 and mcX < termX-1 then
          showFuel = not showFuel
          drawElement(1, 2, termX, termY, white, black, "")
          turtleControlScreen(thisTurtle)
        end
        return
      elseif mcY == 12 and mButton == 1 then
        if mcX > 2 and mcX < 5 then                     -- DOWN
          drawElement(3, 12, 2, 2, black, white, "\\/") -- Down
          netSend(allTurtles[thisTurtle].cc, "move", "down")
          sleep(0.01)
          drawElement(3, 12, 2, 2, nil, gray, "\\/")    -- Down
        elseif mcX > 4 and mcX < 7 then                 -- Back
          drawElement(5, 12, 2, 2, white, gray, "\\/")  -- Back
          netSend(allTurtles[thisTurtle].cc, "move", "back")
          sleep(0.01)
          drawElement(5, 12, 2, 2, black, white, "\\/") -- Back
        elseif mcX > 6 and mcX < 9 then                 -- Obstacle check
          allTurtles[thisTurtle].dirCheck = not allTurtles[thisTurtle].dirCheck
          netSend(allTurtles[thisTurtle].cc, "dcToggle", allTurtles[thisTurtle].dirCheck)
        end
        return
      elseif mcY == 13 and mButton == 1 then
        if mcX > 2 and mcX < 5 then                     -- DOWN
          drawElement(3, 12, 2, 2, black, white, "\\/") -- Down
          netSend(allTurtles[thisTurtle].cc, "move", "down")
          sleep(0.01)
          drawElement(3, 12, 2, 2, nil, gray, "\\/")    -- Down
        elseif mcX > 4 and mcX < 7 then                 -- Back
          drawElement(5, 12, 2, 2, white, gray, "\\/")  -- Back
          netSend(allTurtles[thisTurtle].cc, "move", "back")
          sleep(0.01)
          drawElement(5, 12, 2, 2, black, white, "\\/") -- Back
        elseif mcX > 6 and mcX < 9 then                 -- Obstacle check
          allTurtles[thisTurtle].dirCheck = not allTurtles[thisTurtle].dirCheck
          netSend(allTurtles[thisTurtle].cc, "dcToggle", allTurtles[thisTurtle].dirCheck)
          -- Inventory
        elseif mcX > 11 and mcX < 24 then
          netSend(allTurtles[thisTurtle].cc, "inv", "inv")
          drawElement(1, 2, termX, termY, nil, black, "")
          runState = "Inventory"
          drawCLI()
        end
        return
      elseif (mcY == 15 or mcY == 16) and mButton == 1 then -- Refresh GPS fix
        if mcX > 15 and mcX < 25 then
          drawElement(16, 15, 9, 1, white, gray, "Refresh")
          drawElement(16, 16, 9, 1, nil, nil, "GPS Fix")
          netSend(allTurtles[thisTurtle].cc, "gpsLoc")
          sleep(0.01)
          drawElement(16, 15, 9, 1, black, nil, "Refresh")
          drawElement(16, 16, 9, 1, nil, nil, "GPS Fix")
          local netREvent = { rednet.receive(2) }
          if not netREvent[1] then return end
          if netREvent[1] == thisTurtle then
            newSettings = netREvent[2]
          end
          turtleControlScreen(thisTurtle)
        end
        return
      elseif (mcY == 17 or mcY == 18) and mButton == 1 then -- Export to pocketgps
        if mcX > 15 and mcX < 25 and allTurtles[thisTurtle].loc.x ~= "No GPS Fix" then
          drawElement(16, 17, 9, 1, white, silver, "Export")
          drawElement(16, 18, 9, 1, nil, nil, "to pgps")
          local pgpsPlaces = fs.open("/.places", fs.exists("/.places") and "a" or "w")
          pgpsPlaces.writeLine(allTurtles[thisTurtle].loc.x .. ", " .. allTurtles[thisTurtle].loc.y .. ", " .. allTurtles[thisTurtle].loc.z .. ", " .. allTurtles[thisTurtle].name)
          pgpsPlaces.close()
          sleep(0.01)
          drawElement(16, 17, 9, 1, black, nil, "Export")
          drawElement(16, 18, 9, 1, nil, nil, "to pgps")
        end
        return
      end
    elseif runState == "Inventory" then
      if mcY == 2 and mButton == 1 then        -- Close
        drawElement(1, 2, termX, termY, nil, black, "")
        runState = tmpState
        if runState == "List" or runState == "Remote" or runState == "Inventory" then drawCLI() end
        return
      elseif mcY == 17 and mButton == 1 then
        if mcX > 12 and mcX < 20 then
          if tDirection == "Up" then
            tDirection = "Down"
          elseif tDirection == "Down" then
            tDirection = "Forward"
          elseif tDirection == "Forward" then
            tDirection = "Up"
          end
          drawElement(13, 17, 1, 1, silver, black, tDirection .. "     ")
          return
        end
      elseif mcY == termY - 1 and mButton == 1 then -- Refresh inventory
        drawElement((termX / 2) - 9, termY-1, 1, 1, black, silver, " Refresh Inventory ")
        netSend(allTurtles[thisTurtle].cc, "inv", "inv")
        sleep(0.01)
        drawElement((termX / 2) - 9, termY-1, 1, 1, white, brown, " Refresh Inventory ")
        return
      end
      if mcX < 15 and mButton == 1 then        -- Inventory
        if mcY == 7 then      -- Row 1
          if mcX == 3 or mcX == 4 then       -- slot 1
            netSend(allTurtles[thisTurtle].cc, "sel", 1)
          elseif mcX == 6 or mcX == 7 then   -- slot 2
            netSend(allTurtles[thisTurtle].cc, "sel", 2)
          elseif mcX == 9 or mcX == 10 then  -- slot 3
            netSend(allTurtles[thisTurtle].cc, "sel", 3)
          elseif mcX == 12 or mcX == 13 then -- slot 4
            netSend(allTurtles[thisTurtle].cc, "sel", 4)
          end
        elseif mcY == 9 then  -- Row 2
          if mcX == 3 or mcX == 4 then       -- slot 1
            netSend(allTurtles[thisTurtle].cc, "sel", 5)
          elseif mcX == 6 or mcX == 7 then   -- slot 2
            netSend(allTurtles[thisTurtle].cc, "sel", 6)
          elseif mcX == 9 or mcX == 10 then  -- slot 3
            netSend(allTurtles[thisTurtle].cc, "sel", 7)
          elseif mcX == 12 or mcX == 13 then -- slot 4
            netSend(allTurtles[thisTurtle].cc, "sel", 8)
          end
        elseif mcY == 11 then -- Row 3
          if mcX == 3 or mcX == 4 then       -- slot 1
            netSend(allTurtles[thisTurtle].cc, "sel", 9)
          elseif mcX == 6 or mcX == 7 then   -- slot 2
            netSend(allTurtles[thisTurtle].cc, "sel", 10)
          elseif mcX == 9 or mcX == 10 then  -- slot 3
            netSend(allTurtles[thisTurtle].cc, "sel", 11)
          elseif mcX == 12 or mcX == 13 then -- slot 4
            netSend(allTurtles[thisTurtle].cc, "sel", 12)
          end
        elseif mcY == 13 then -- Row 4
          if mcX == 3 or mcX == 4 then       -- slot 1
            netSend(allTurtles[thisTurtle].cc, "sel", 13)
          elseif mcX == 6 or mcX == 7 then   -- slot 2
            netSend(allTurtles[thisTurtle].cc, "sel", 14)
          elseif mcX == 9 or mcX == 10 then  -- slot 3
            netSend(allTurtles[thisTurtle].cc, "sel", 15)
          elseif mcX == 12 or mcX == 13 then -- slot 4
            netSend(allTurtles[thisTurtle].cc, "sel", 16)
          end
        end
      elseif mcX > 14 then                     -- Refuel/Place/Break/Equip
        if mcY == 7 then           -- Refuel
          drawElement(16, 7, 9, 1, white, gray, " Refuel")
          if mButton == 1 then
            netSend(allTurtles[thisTurtle].cc, "refuel", 1)
          elseif mButton == 2 then
            netSend(allTurtles[thisTurtle].cc, "refuel", 5)
          elseif mButton == 3 then
            netSend(allTurtles[thisTurtle].cc, "refuel", 10)
          end
          sleep(0.01)
          drawElement(16, 7, 9, 1, black, yellow, " Refuel")
          return
        elseif mcY == 9 and mButton ~= 3 then  -- Place or engrave
          drawElement(16, 9, 9, 1, white, gray, "Place")
          if mButton == 1 then     -- Place
            netSend(allTurtles[thisTurtle].cc, "put", tDirection)
          elseif mButton == 2 then -- Engrave
            runState = "engrave"
          end
          sleep(0.01)
          drawElement(16, 9, 9, 1, black, green, "Place")
          return
        elseif mcY == 11 and mButton ~= 3 then -- All units, break and attack!
          drawElement(16, 11, 9, 1, white, gray, "Break")
          if mButton == 1 then     -- Break
            netSend(allTurtles[thisTurtle].cc, "dig", tDirection)
          elseif mButton == 2 then -- Attack
            netSend(allTurtles[thisTurtle].cc, "atk", tDirection)
          end
          sleep(0.01)
          drawElement(16, 11, 9, 1, black, red, "Break")
          return
        elseif mcY == 13 and mButton ~= 3 then -- Equip
          drawElement(16, 13, 9, 1, white, gray, "Equip")
          if mButton == 1 then     -- Equip left
            netSend(allTurtles[thisTurtle].cc, "eqp", "left")
          elseif mButton == 2 then -- Equip right
            netSend(allTurtles[thisTurtle].cc, "eqp", "right")
          end
          sleep(0.01)
          drawElement(16, 13, 9, 1, black, silver, "Equip")
          return
        end
      end
    elseif runState == "List" then
      if mcY == 1 and mButton == 1 then
        if mcX > 0 and mcX < 4 then -- Fuel filter
          fuelFilter = not fuelFilter
          filterTurtleList()
          drawElement(1, 3, termX, termY, nil, black, "")
          drawCLI()
          return
        elseif mcX > termX - 3 and mcX <= termX then
         -- Quit
          kernelState = false
          runState = "quit"
          return
        end
       -- ALL ON/OFF
      elseif mcY == 2 and mButton == 1 then
        if mcX < termX / 2 then
          netSend("ALL", "rds", true)
        elseif mcX > termX / 2 then
          netSend("ALL", "rds", false)
        end
        return
       -- Open a turtle's properties/control screen
      elseif mcY > 3 and mcY < 19 then
        local magicNumber = ((pageNum - 1) * 23) + pageNum
        local xPos, yPos = 1, 4
        for i = magicNumber, #filteredTurtles do
          if mcX >= xPos and mcX < xPos + 8 and mcY == yPos then
            if mButton == 1 or mButton == 2 then
              if not filteredTurtles[i].lockState then
                drawElement(1, 2, termX, termY, nil, black, "")
                turtleControlScreen(filteredTurtles[i].atList)
              end
              return
            elseif mButton == 3 then
              thisTurtle = filteredTurtles[i].atList
              runState = "password"
              return
            end
          end
          yPos = yPos + 2
          if yPos > 19 then yPos = 4 xPos = xPos + 9 end
          if xPos > termX - 7 then break end
        end
        return
       -- Page Navigation via click
      elseif mcY == termY and mButton == 1 then -- Bottom row of screen
        if mcX < termX / 2 - 3 then             -- Page Back
          if pageNum > 1 then
            pageNum = pageNum - 1
            drawMainUI()
            drawNaviUI()
          end
          return
        elseif mcX > termX / 2 - 3 and mcX < termX / 2 + 3 then -- Page Numbers (Go To Page dialogue)
          runState = "goPage"
          return
        elseif mcX > termX / 2 + 3 then         -- Page Forward
          pageNum = math.min(pageNum + 1, numPages)
          if pageNum == numPages and numPages > 1 then
            drawElement(2, 4, termX, termY, nil, black, "")
          end
          drawMainUI()
          drawNaviUI()
          return
        end
      end
    end
  --end
end
 
local function mScroll()
  --while true do
    local _, data = os.pullEvent("mouse_scroll")
    if runState == "List" then
      if data == -1 and pageNum > 1 then
        pageNum = math.max(1, pageNum - 1)
      elseif data == 1 and pageNum < numPages then
        pageNum = math.min(pageNum + 1, numPages)
        if pageNum == numPages and numPages > 1 then
          drawElement(2, 4, termX, termY, nil, black, "")
        end
      end
      drawMainUI()
      drawNaviUI()
    end
  --end
end
 
local function dataPoller()
  --while true do
    local _, timerID = os.pullEvent("timer")
    if timerID == pollTimer then
      if runState == "List" then
        for i = #allTurtles, 1, -1 do
          if allTurtles[i].quietCount > 1 then
            table.remove(allTurtles, i)
            removal = true
          else
            allTurtles[i].quietCount = allTurtles[i].quietCount + 1
          end
        end
        --sortTurtleList()
        if removal then
          drawElement(1, 4, termX, termY-1, nil, black, "")
          drawMainUI()
          drawNaviUI()
          removal = false
        end
        --[[
      else
        for i = 1, #allTurtles, 1 do
          allTurtles[i].quietCount = allTurtles[i].quietCount + 1
        end
        ]]--
      end
      netSend("ALL", "gtrQRY", "gtrQRY")
      if not timerDelay then
        pollTimer = os.startTimer(5)
      end
      --return
    end
  --end
end
 
local function gtrKernel()
  if kernelState then
    if runState == "List" or runState == "Remote" or runState == "Inventory" or runState == "Help" then
      parallel.waitForAny(keyClick, mClick, mScroll, netReceive, dataPoller)
    elseif runState == "Edit" then
      parallel.waitForAny(editEntry, netReceive)
    elseif runState == "password" then
      parallel.waitForAny(enterPassword, netReceive)
    elseif runState == "engrave" then
      parallel.waitForAny(getSignText, netReceive)
    elseif runState == "shellCmd" then
      parallel.waitForAny(shellCommand, netReceive)
    elseif runState == "goPage" then
      parallel.waitForAny(goToPage, netReceive)
    elseif runState == "color" then
      parallel.waitForAny(colorPicker, netReceive, dataPoller)
    end
  end
  if runState == "quit" then
    kernelState = false
  end
  if kernelState and timerDelay and not inputting then
    timerDelay = false
    pollTimer = os.startTimer(5)
  end
  return kernelState
end
 
local function initMe()
  term.setBackgroundColor(black)
  term.clear()
  drawElement(2, 2, 18, 1, white, black, "Initializing . . .")
  local ccLabel = os.getComputerLabel()
  if ccLabel == nil or ccLabel == "" then
    os.setComputerLabel("Remote")
  end
  for _, side in ipairs(rs.getSides()) do
    if peripheral.isPresent(side) then
      if peripheral.getType(side) == "modem" then
        if peripheral.call(side, "isWireless") then
          rednet.open(side)
          netSide = side
          break
        end
      end
    end
  end
  if netSide == "none" then
    term.clear()
    drawElement(2, 2, 1, 1, red, nil, "No wireless")
    drawElement(2, 3, 1, 1, nil, nil, "modem detected!")
    drawElement(2, 5, 1, 1, nil, nil, "gtRemote REQUIRES")
    drawElement(2, 6, 1, 1, nil, nil, "a wireless modem.")
    term.setCursorPos(1, 9)
    runState = "quit"
    err = "YES"
    return
  end
  kernelState = true
  runState = "List"
  drawElement(2, 4, 1, 1, white, nil, "Searching for hosts . . .")
  netSend("ALL", "gtrQRY", "gtrQRY")
  pollTimer = os.startTimer(5)
  term.clear()
  drawCLI()
end
 
initMe()
 
repeat
  gtrKernel()
  if runState == "quit" then kernelState = false end
  if not kernelState then
    term.setBackgroundColor(black)
    term.setTextColor(white)
    if err == "NO" then
      term.clear()
      term.setCursorPos(1, 1)
    end
    rednet.close(netSide)
    return
  end
until kernelState == false