civilwargeeky

Quarry 3.5.3

Aug 31st, 2014
3,454
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. --Civilwargeeky's Quarry Program--
  2.   VERSION = "3.5.3"
  3. --[[
  4. Recent Changes:
  5.   Changes with receiver
  6.   Fixed Bug with modem in most recent version of CC
  7.   Ore Quarry!!!
  8.   Completely redid the system of dropping items off
  9.   Improved session restoring for those using fuel
  10.   Added New Rednet Support
  11.   New Arguments!
  12.     -oreQuarry [t/f] This will start an oreQuarry :D
  13.     -dumpCompareItems [t/f] If true, the oreQuarry will drop off junk compare items
  14.     -extraDropItems [force] Tells the oreQuarry that you want to have extra drop-off items, like cobblestone
  15.     -atChest [force] Using this with -resume will tell the turtle that it is at its chest, and needs to go back to where it was
  16. ]]
  17. --Defining things
  18. civilTable = nil; _G.civilTable = {}; setmetatable(civilTable, {__index = _G}); setfenv(1,civilTable)
  19. originalDay = os.day() --Used in logging
  20. numResumed = 0 --Number of times turtle has been resumed
  21. -------Defaults for Arguments----------
  22. --Arguments assignable by text
  23. x,y,z = 3,3,3 --These are just in case tonumber fails
  24. inverted = false --False goes from top down, true goes from bottom up [Default false]
  25. rednetEnabled = false --Default rednet on or off  [Default false]
  26. --Arguments assignable by tArgs
  27. dropSide = "front" --Side it will eject to when full or done [Default "front"]
  28. careAboutResources = true --Will not stop mining once inventory full if false [Default true]
  29. doCheckFuel = true --Perform fuel check [Default true]
  30. doRefuel = false --Whenever it comes to start location will attempt to refuel from inventory [Default false]
  31. keepOpen = 1 --How many inventory slots it will attempt to keep open at all times [Default 1]
  32. fuelSafety = "moderate" --How much fuel it will ask for: safe, moderate, and loose [Default moderate]
  33. saveFile = "Civil_Quarry_Restore" --Where it saves restore data [Default "Civil_Quarry_Restore"]
  34. doBackup = true --If it will keep backups for session persistence [Default true]
  35. uniqueExtras = 8 --How many different items (besides cobble) the turtle expects. [Default 8]
  36. maxTries = 50 --How many times turtle will try to dig a block before it "counts" bedrock [Default 50]
  37. gpsEnabled = false -- If option is enabled, will attempt to find position via GPS api [Default false]
  38. gpsTimeout = 3 --The number of seconds the program will wait to get GPS coords. Not in arguments [Default 3]
  39. logging = true --Whether or not the turtle will log mining runs. [Default ...still deciding]
  40. logFolder = "Quarry_Logs" --What folder the turtle will store logs in [Default "Quarry_Logs"]
  41. logExtension = "" --The extension of the file (e.g. ".txt") [Default ""]
  42. startDown = 0 --How many blocks to start down from the top of the mine [Default 0]
  43. enderChestEnabled = false --Whether or not to use an ender chest [Default false]
  44. enderChestSlot = 16 --What slot to put the ender chest in [Default 16]
  45. oreQuarry = false --Enables ore quarry functionality [Default false]
  46. dumpCompareItems = true --If ore quarry, the turtle will dump items compared to (like cobblestone) [Default true]
  47. --Standard number slots for fuel (you shouldn't care)
  48. fuelTable = { --Will add in this amount of fuel to requirement.
  49. safe = 1000,
  50. moderate = 200,
  51. loose = 0 } --Default 1000, 200, 0
  52. --Standard rednet channels
  53. channels = {
  54. send = os.getComputerID() + 1  ,
  55. receive = os.getComputerID() + 101 ,
  56. confirm = "Turtle Quarry Receiver",
  57. message = "Civil's Quarry",
  58. }
  59.  
  60. --AVERAGE USER: YOU DON'T CARE BELOW THIS POINT
  61.  
  62. local help_paragraph = [[
  63. Welcome!: Welcome to quarry help. Below are help entries for all parameters. Examples and tips are at the bottom.
  64. -Default: This will force no prompts. If you use this and nothing else, only defaults will be used.
  65. -dim: [length] [width] [height] This sets the dimensions for the quarry
  66. -invert: [t/f] If true, quarry will be inverted (go up instead of down)
  67. -rednet: [t/f] If true and you have a wireless modem on the turtle, will attempt to make a rednet connection for sending important information to a screen
  68. -restore / -resume: If your quarry stopped in the middle of its run, use this to resume at the point where the turtle was. Not guarenteed to work properly. For more accurate location finding, check out the -GPS parameter
  69. -oreQuarry: [t/f] If true, the turtle will use ore quarry mode. It will not mine the blocks that are placed in the turtle initially. So if you put in stone, it will ignore stone blocks and only mine ores.
  70. -atChest: [force] This is for use with "-restore," this will tell the restarting turtle that it is at its home chest, so that if it had gotten lost, it now knows where it is.
  71. -doRefuel: [t/f] If true, the turtle will refuel itself with coal and planks it finds on its mining run
  72. -doCheckFuel: [t/f] If you for some reason don't want the program to check fuel usage, set to false. This is honestly a hold-over from when the refueling algorithm was awful...
  73. -uniqueExtras: [number] The expected number of slots filled with low-stacking items like ore. Higher numbers request more fuel.
  74. -chest: [side] This specifies what side the chest at the end will be on. You can say "top", "bottom", "front", "left", or "right"
  75. -enderChest: This one is special. If you use "-enderChest true" then it will use an enderChest in the default slot. However, you can also do "-enderChest [slot]" then it will take the ender chest from whatever slot you tell it to. Like 7... or 14... or whatever.
  76. -GPS: [force] If you use "-GPS" and there is a GPS network, then the turtle will record its first two positions to precisly calculate its position if it has to restart. This will only take two GPS readings
  77. -sendChannel: [number] This is what channel your turtle will send rednet messages on
  78. -receiveChannel: [number] This is what channel your turtle will receive rednet messages on
  79. -startY: [current Y coord] Randomly encountering bedrock? This is the parameter for you! Just give it what y coordinate you are at right now. If it is not within bedrock range, it will never say it found bedrock
  80. -extraDropItems: [force] If oreQuarry then this will prompt the user for extra items to drop, but not compare to (like cobblestone)
  81. -dumpCompareItems: [t/f] If oreQuarry and this is true, the turtle will dump off compare blocks instead of storing them in a chest
  82. -maxTries: [number] This is the number of times the turtle will try to dig before deciding its run into bedrock.
  83. -logging: [t/f] If true, will record information about its mining run in a folder at the end of the mining run
  84. -doBackup: [t/f] If false, will not back up important information and cannot restore, but will not make an annoying file (Actually I don't really know why anyone would use this...)
  85. -saveFile: [word] This is what the backup file will be called
  86. -logFolder: [word] The folder that quarry logs will be stored in
  87. -logExtension: [word] The extension given to each quarry log (e.g. ".txt" or ".notepad" or whatever)
  88. -keepOpen: [number] This is the number of the slots the turtle will make sure are open. It will check every time it mines
  89. -careAboutResources: [t/f] Who cares about the materials! If set to false, it will just keep mining when its inventory is full
  90. -startDown: [number] If you set this, the turtle will go down this many blocks from the start before starting its quarry
  91.   =
  92.   C _ |
  93.       |
  94.       |
  95.       |
  96.       |_ _ _ _ >
  97. -manualPos: [xPos] [zPos] [yPos] [facing] This is for advanced use. If the server reset when the turtle was in the middle of a 100x100x100 quarry, fear not, you can now manually set the position of the turtle. yPos is always positive. The turtle's starting position is 0, 1, 1, 0. Facing is measured 0 - 3. 0 is forward, and it progresses clockwise. Example- "-manualPos 65 30 30 2"
  98. -help: Thats what this is :D
  99. Examples: Everything below is examples and tips for use
  100. Important Note:
  101.  None of the above parameters are necessary. They all have default values, and the above are just if you want to change them.
  102. Examples [1]:
  103.  Want to just start a quarry from the interface, without going through menus? It's easy! Just use some parameters. Assume you called the program "quarry." To start a 10x6x3 quarry, you just type in "quarry -dim 10 6 3 -default".
  104.   You just told it to start a quarry with dimensions 10x6x3, and "-default" means it won't prompt you about invert or rednet. Wasn't that easy?
  105. Examples [2]:
  106.   Okay, so you've got the basics of this now, so if you want, you can type in really long strings of stuff to make the quarry do exactly what you want. Now, say you want a 40x20x9, but you want it to go down to diamond level, and you're on the surface (at y = 64). You also want it to send rednet messages to your computer so you can see how its doing.
  107. Examples [2] [cont.]:
  108.   Oh yeah! You also want it to use an ender chest in slot 12 and restart if the server crashes. Yeah, you can do that. You would type
  109.   "quarry -dim 40x20x9 -invert false -startDown 45 -rednet true -enderChest 12 -restore"
  110.   BAM. Now you can just let that turtle do it's thing
  111. Tips:
  112.  The order of the parameters doesn't matter. "quarry -invert false -rednet true" is the same as "quarry -rednet true -invert false"
  113.  
  114.   Capitalization doesn't matter. "quarry -iNVErt FALSe" does the same thing as "quarry -invert false"
  115. Tips [cont.]:
  116.  For [t/f] parameters, you can also use "yes" and "no" so "quarry -invert yes"
  117.  
  118.  For [t/f] parameters, it only cares about the first letter. So you can use "quarry -invert t" or "quarry -invert y"
  119. Tips [cont.]:
  120.  If you are playing with fuel turned off, the program will automatically change settings for you so you don't have to :D
  121.  
  122.   If you want, you can load this program onto a computer, and use "quarry -help" so you can have help with the parameters whenever you want.
  123. Internal Config:
  124.   At the top of this program is an internal configuration file. If there is some setup that you use all the time, you can just change the config value at the top and run "quarry -default" for a quick setup.
  125.  
  126.   You can also use this if there are settings that you don't like the default value of.
  127. ]]
  128.  
  129. --Parsing help for display
  130. --[[The way the help table works:
  131. All help indexes are numbered. There is a help[i].title that contains the title,
  132. and the other lines are in help[i][1] - help[i][#help[i] ]
  133. Different lines (e.g. other than first) start with a space.
  134. As of now, the words are not wrapped, fix that later]]
  135. local help = {}
  136. local i = 0
  137. local titlePattern = ".-%:" --Find the beginning of the line, then characters, then a ":"
  138. local textPattern = "%:.+" --Find a ":", then characters until the end of the line
  139. for a in help_paragraph:gmatch("\n?.-\n") do --Matches in between newlines
  140. local current = string.sub(a,1,-2).."" --Concatenate Trick
  141. if string.sub(current,1,1) ~= " " then
  142. i = i + 1
  143. help[i] = {}
  144. help[i].title = string.sub(string.match(current, titlePattern),1,-2)..""
  145. help[i][1] = string.sub(string.match(current,textPattern) or " ",3,-1)
  146. elseif string.sub(current,1,1) == " " then
  147. table.insert(help[i], string.sub(current,2, -1).."")
  148. end
  149. end
  150.  
  151. local supportsRednet
  152. if peripheral.find then
  153.  supportsRednet = peripheral.find("modem") or false
  154. else
  155.  supportsRednet = (peripheral.getType("right") == "modem") or false
  156. end
  157.  
  158. local tArgs = {...}
  159. --Pre-defining variables
  160.      xPos,yPos,zPos,facing,percent,mined,moved,relxPos, rowCheck, connected, isInPath, layersDone, attacked, startY, chestFull, gotoDest, atChest, fuelLevel, numDropOffs, allowedItems, compareSlots, dumpSlots, selectedSlot, extraDropItems
  161.    = 0,   1,   1,   0,     0,      0,    0,    1,       true   ,  false,     true,     1,          0,        0,      false,     "",       false,   0,         0,           {},             {},           {},      1,            false
  162.    
  163. for i=1, 16 do --Initializing various inventory management tables
  164.  allowedItems[i] = 0 --Number of items allowed in slot when dropping items
  165.  dumpSlots[i] = false --Does this slot contain junk items?
  166. end --compareSlots is a table of the compare slots, not all slots with a condition
  167. totals = {cobble = 0, fuel = 0, other = 0} -- Total for display (cannot go inside function), this goes up here because many functions use it
  168.  
  169. function resetDumpSlots()
  170.    for i=1, 16 do
  171.      if oreQuarry then
  172.        if turtle.getItemCount(i) > 0 and i~= enderChestSlot then
  173.          dumpSlots[i] = true
  174.        else
  175.          dumpSlots[i] = false
  176.        end
  177.      else
  178.        dumpSlots[i] = false
  179.      end
  180.    end
  181.    if not oreQuarry and enderChestSlot == 1 then
  182.      dumpSlots[2] = true
  183.    elseif not oreQuarry then
  184.      dumpSlots[1] = true
  185.    end
  186. end
  187.        
  188.  
  189. local function copyTable(tab) local toRet = {}; for a, b in pairs(tab) do toRet[a] = b end; return toRet end --This goes up here because it is a basic utility
  190.  
  191. --NOTE: rowCheck is a bit. true = "right", false = "left"
  192.    
  193. local foundBedrock = false
  194.  
  195. local getFuel, checkFuel
  196. if turtle then
  197.  getFuel = turtle.getFuelLevel  --This is for cleanup at the end
  198.  do --Common variable name...
  199.  local flag = turtle.getFuelLevel() == "unlimited"--Unlimited screws up my calculations
  200.  if flag then --Fuel is disabled
  201.    turtle.getFuelLevel = function() return math.huge end --Infinite Fuel
  202.  end --There is no "else" because it will already return the regular getFuel
  203.  end
  204.  checkFuel = turtle.getFuelLevel --Just an alias for backwards compat
  205.  
  206.  turtle.select(1) --To ensure this is correct
  207. end
  208.  
  209.  
  210. function select(slot)
  211.  if slot ~= selectedSlot then
  212.    selectedSlot = slot
  213.    return turtle.select(slot), selectedSlot
  214.  end
  215. end
  216.  
  217.  
  218. -----------------------------------------------------------------
  219. --Input Phase
  220. local function screen(xPos,yPos)
  221. xPos, yPos = xPos or 1, yPos or 1
  222. term.setCursorPos(xPos,yPos); term.clear(); end
  223. local function screenLine(xPos,yPos)
  224. term.setCursorPos(xPos,yPos); term.clearLine(); end
  225.  
  226. screen(1,1)
  227. print("----- Welcome to Quarry! -----")
  228. print("")
  229.  
  230. local sides = {top = "top", right = "right", left = "left", bottom = "bottom", front = "front"} --Used to whitelist sides
  231. local changedT, tArgsWithUpper = {}, {}
  232. changedT.new = function(key, value) table.insert(changedT,{key, value}) end --Numeric list of lists
  233. local function capitalize(text) return (string.upper(string.sub(text,1,1))..string.sub(text,2,-1)) end
  234. for i=1, #tArgs do tArgsWithUpper[i] = tArgs[i]; tArgsWithUpper[tArgsWithUpper[i]] = i; tArgs[i] = tArgs[i]:lower(); tArgs[tArgs[i]] = i end --My signature key-value pair system, now with upper
  235.  
  236. local restoreFound, restoreFoundSwitch = false --Initializing so they are in scope
  237. function addParam(name, displayText, formatString, forcePrompt, trigger, variableOverride) --To anyone that doesn't understand this very well, probably not your best idea to go in here.
  238.   if trigger == nil then trigger = true end --Defaults to being able to run
  239.   if not trigger then return end --This is what the trigger is for. Will not run if trigger not there
  240.   if restoreFoundSwitch or tArgs["-default"] then forcePrompt = false end --Don't want to prompt if these
  241.   local toGetText = name:lower() --Because all params are now lowered
  242.   local formatType = formatString:match("^%a+"):lower() or error("Format String Unknown: "..formatString) --Type of format string
  243.   local args = formatString:sub(({formatString:find(formatType)})[2] + 2).."" --Everything in formatString but the type and space
  244.   local variable = variableOverride or name --Goes first to the override for name
  245.   local func = loadstring("return "..variable)
  246.   setfenv(func,getfenv(1))
  247.   local originalValue = assert(func)() --This is the default value, for checking to add to changed table
  248.   if originalValue == nil then error("From addParam, \""..variable.."\" returned nil",2) end --I may have gotten a wrong variable name
  249.   local givenValue, toRet --Initializing for use
  250.   if tArgs["-"..toGetText] then
  251.     givenValue = tArgsWithUpper[tArgs["-"..toGetText]+1] --This is the value after the desired parameter
  252.   elseif forcePrompt then
  253.     write(displayText.."? ")
  254.     givenValue = io.read()
  255.   end
  256.   if formatType == "force" then --This is the one exception. Should return true if givenValue is nothing
  257.     toRet = (tArgs["-"..toGetText] and true) or false --Will return true if param exists, otherwise false
  258.   end
  259.   if not (givenValue or toRet) then return end --Don't do anything if you aren't given anything. Leave it as default, except for "force"
  260.   if formatType == "boolean" then --All the format strings will be basically be put through a switch statement
  261.     toRet = givenValue:sub(1,1):lower() == "y" or givenValue:sub(1,1):lower() == "t" --Accepts true or yes
  262.     if formatString == "boolean special" then
  263.       toRet = givenValue:sub(1,1):lower() ~= "n" and givenValue:sub(1,1):lower() ~= "f" --Accepts anything but false or no
  264.     end
  265.   elseif formatType == "string" then
  266.     toRet = givenValue:match("^[%w%.]+") --Basically anything not a space or control character etc
  267.   elseif formatType == "number" then
  268.     toRet = tonumber(givenValue) --Note this is a local, not the above so we don't change anything
  269.     if not toRet then return end --We need a number... Otherwise compare errors
  270.     toRet = math.abs(math.floor(toRet)) --Get proper integers
  271.     local startNum, endNum = formatString:match("(%d+)%-(%d+)") --Gets range of numbers
  272.     startNum, endNum = tonumber(startNum), tonumber(endNum)
  273.     if not ((toRet >= startNum) and (toRet <= endNum)) then return end --Can't use these
  274.   elseif formatType == "side" then
  275.     local exclusionTab = {} --Ignore the wizardry here. Just getting arguments without format string
  276.     for a in args:gmatch("%S+") do exclusionTab[a] = true end --This makes a list of the sides to not include
  277.     if not exclusionTab[givenValue] then toRet = sides[givenValue] end --If side is not excluded
  278.   elseif formatType == "list" then
  279.     toRet = {}
  280.     for a in args:gmatch("[^,]") do
  281.       table.insert(toRet,a)
  282.     end
  283.   elseif formatType == "force" then --Do nothing, everything is already done
  284.   else error("Improper formatType",2)
  285.   end
  286.   if toRet == nil then return end --Don't want to set variables to nil... That's bad
  287.   tempParam = toRet --This is what loadstring will see :D
  288.   local func = loadstring(variable.." = tempParam")
  289.   setfenv(func, getfenv(1))
  290.   func()
  291.   tempParam = nil --Cleanup of global
  292.   if toRet ~= originalValue and displayText ~= "" then
  293.     changedT.new(displayText, tostring(toRet))
  294.   end
  295.   return toRet
  296. end
  297.  
  298. --Check if it is a turtle
  299. if not(turtle or tArgs["help"] or tArgs["-help"] or tArgs["-?"] or tArgs["?"]) then --If all of these are false then
  300.   print("This is not a turtle, you might be looking for the \"Companion Rednet Program\" \nCheck My forum thread for that")
  301.   print("Press 'q' to quit, or any other key to start help ")
  302.   if ({os.pullEvent("char")})[2] ~= "q" then tArgs.help = true else error("",0) end
  303. end
  304.  
  305. if tArgs["help"] or tArgs["-help"] or tArgs["-?"] or tArgs["?"] then
  306.   print("You have selected help, press any key to continue"); print("Use arrow keys to navigate, q to quit"); os.pullEvent("key")
  307.   local pos = 1
  308.   local key = 0
  309.   while pos <= #help and key ~= keys.q do
  310.     if pos < 1 then pos = 1 end
  311.     screen(1,1)
  312.     print(help[pos].title)
  313.     for a=1, #help[pos] do print(help[pos][a]) end
  314.     repeat
  315.       _, key = os.pullEvent("key")
  316.     until key == 200 or key == 208 or key == keys.q
  317.     if key == 200 then pos = pos - 1 end
  318.     if key == 208 then pos = pos + 1 end
  319.   end
  320.   error("",0)
  321. end
  322.  
  323. --Saving
  324. addParam("doBackup", "Backup Save File", "boolean")
  325. addParam("saveFile", "Save File Name", "string")
  326.  
  327. restoreFound = fs.exists(saveFile)
  328. restoreFoundSwitch = (tArgs["-restore"] or tArgs["-resume"] or tArgs["-atchest"]) and restoreFound
  329. if restoreFoundSwitch then
  330.   local file = fs.open(saveFile,"r")
  331.   local test = file.readAll() ~= ""
  332.   file.close()
  333.   if test then
  334.     os.run(getfenv(1),saveFile) --This is where the actual magic happens
  335.     numResumed = numResumed + 1
  336.     if turtle.getFuelLevel() ~= math.huge then --If turtle uses fuel
  337.       if fuelLevel - turtle.getFuelLevel() == 1 then
  338.         if facing == 0 then xPos = xPos + 1
  339.         elseif facing == 2 then xPos = xPos - 1
  340.         elseif facing == 1 then zPos = zPos + 1
  341.         elseif facing == 3 then zPos = zPos - 1 end
  342.       elseif fuelLevel - turtle.getFuelLevel() ~= 0 then
  343.         print("Very Strange Fuel in Restore Section...")
  344.         print("Current: ",turtle.getFuelLevel())
  345.         print("Saved: ",fuelLevel)
  346.         print("Difference: ",fuelLevel - turtle.getFuelLevel())
  347.         os.pullEvent("char")
  348.       end
  349.      end
  350.     if gpsEnabled then --If it had saved gps coordinates
  351.       print("Found GPS Start Coordinates")
  352.       local currLoc = {gps.locate(gpsTimeout)} or {}
  353.       local backupPos = {xPos, yPos, zPos} --This is for comparing to later
  354.       if #currLoc > 0 and #gpsStartPos > 0 and #gpsSecondPos > 0 then --Cover all the different positions I'm using
  355.         print("GPS Position Successfully Read")
  356.         if currLoc[1] == gpsStartPos[1] and currLoc[3] == gpsStartPos[3] then --X coord, y coord, z coord in that order
  357.           xPos, yPos, zPos = 0,1,1
  358.           if facing ~= 0 then turnTo(0) end
  359.           print("Is at start")
  360.         else
  361.           if inverted then --yPos setting
  362.           ------------------------------------------------FIX THIS
  363.           end
  364.           local a, b = copyTable(gpsStartPos), copyTable(gpsSecondPos) --For convenience
  365.           if b[3] - a[3] == -1 then--If went north (-Z)
  366.             a[1] = a[1] - 1 --Shift x one to west to create a "zero"
  367.             xPos, zPos = -currLoc[3] + a[3], currLoc[1] + -a[1]
  368.           elseif b[1] - a[1] == 1 then--If went east (+X)
  369.             a[3] = a[3] - 1 --Shift z up one to north to create a "zero"
  370.             xPos, zPos = currLoc[1] + -a[1], currLoc[3] + -a[3]
  371.           elseif b[3] - a[3] == 1 then--If went south (+Z)
  372.             a[1] = a[1] + 1 --Shift x one to east to create a "zero"
  373.             xPos, zPos = currLoc[3] + a[3], -currLoc[1] + a[3]
  374.           elseif b[1] - a[1] == -1 then--If went west (-X)
  375.             a[3] = a[3] + 1 --Shift z down one to south to create a "zero"
  376.             xPos, zPos = -currLoc[1] + a[1], -currLoc[3] + a[3]
  377.           else
  378.             print("Improper Coordinates")
  379.             print("GPS Locate Failed, Using Standard Methods")        ----Maybe clean this up a bit to use flags instead.
  380.           end  
  381.         end
  382.         print("X Pos: ",xPos)
  383.         print("Y Pos: ",yPos)
  384.         print("Z Pos: ",zPos)
  385.         print("Facing: ",facing)
  386.         for i=1, 3, 2 do --We want 1 and 3, but 2 could be coming back to start.
  387.           if backupPos[i] ~= currLoc[i] then
  388.             events = {} --We want to remove event queue if not in proper place, so won't turn at end of row or things.
  389.           end
  390.         end
  391.       else
  392.         print("GPS Locate Failed, Using Standard Methods")
  393.       end    
  394.     print("Restore File read successfully. Starting in 3"); sleep(3)
  395.     end
  396.   else
  397.     fs.delete(saveFile)
  398.     print("Restore file was empty, sorry, aborting")
  399.     error("",0)
  400.   end
  401. else --If turtle is just starting
  402.   events = {} --This is the event queue :D
  403.   originalFuel = checkFuel() --For use in logging. To see how much fuel is REALLY used
  404. end
  405.  
  406. --Dimensions
  407. if tArgs["-dim"] then
  408.   local a,b,c = x,y,z
  409.   local num = tArgs["-dim"]
  410.   x = tonumber(tArgs[num + 1]) or x; z = tonumber(tArgs[num + 2]) or z; y = tonumber(tArgs[num + 3]) or y
  411.   if a ~= x then changedT.new("Length", x) end
  412.   if c ~= z then changedT.new("Width", z) end
  413.   if b ~= y then changedT.new("Height", y) end
  414. elseif not (tArgs["-default"] or restoreFoundSwitch) then
  415.   print("What dimensions?")
  416.   print("")
  417.   --This will protect from negatives, letters, and decimals
  418.   term.write("Length? ")
  419.   x = math.floor(math.abs(tonumber(io.read()) or x))
  420.   term.write("Width? ")
  421.   z = math.floor(math.abs(tonumber(io.read()) or z))
  422.   term.write("Height? ")
  423.   y = math.floor(math.abs(tonumber(io.read()) or y))
  424.   changedT.new("Length",x); changedT.new("Width",z); changedT.new("Height",y)
  425. end
  426. --Params: parameter/variable name, display name, type, force prompt, boolean condition, variable name override
  427. --Invert
  428. addParam("invert", "Inverted","boolean", true, nil, "inverted")
  429. addParam("startDown","Start Down","number 1-256")
  430. --Inventory
  431. addParam("chest", "Chest Drop Side", "side front", nil, nil, "dropSide")
  432. addParam("enderChest","Ender Chest Enabled","boolean special", nil, nil, "enderChestEnabled") --This will accept anything (including numbers) thats not "f" or "n"
  433. addParam("enderChest", "Ender Chest Slot", "number 1-16", nil, nil, "enderChestSlot") --This will get the number slot if given
  434. if not enderChestEnabled then enderChestSlot = 0 end --This makes everything better
  435. --Rednet
  436. addParam("rednet", "Rednet Enabled","boolean",true, supportsRednet, "rednetEnabled")
  437. addParam("gps", "GPS Location Services", "force", nil, (not restoreFoundSwitch) and supportsRednet, "gpsEnabled" ) --Has these triggers so that does not record position if restarted.
  438. if gpsEnabled and not restoreFoundSwitch then
  439.   gpsStartPos = {gps.locate(gpsTimeout)} --Stores position in array
  440.   gpsEnabled = #gpsStartPos > 0 --Checks if location received properly. If not, position is not saved
  441. end
  442. addParam("sendChannel", "Rednet Send Channel", "number 1-65535", false, supportsRednet, "channels.send")
  443. addParam("receiveChannel","Rednet Receive Channel", "number 1-65535", false, supportsRednet, "channels.receive")
  444. --Fuel
  445. addParam("uniqueExtras","Unique Items", "number 0-15")
  446. addParam("doRefuel", "Refuel from Inventory","boolean", nil, turtle.getFuelLevel() ~= math.huge) --math.huge due to my changes
  447. addParam("doCheckFuel", "Check Fuel", "boolean", nil, turtle.getFuelLevel() ~= math.huge)
  448. --Logging
  449. addParam("logging", "Logging", "boolean")
  450. addParam("logFolder", "Log Folder", "string")
  451. addParam("logExtension","Log Extension", "string")
  452. --Misc
  453. addParam("startY", "Start Y","number 1-256")
  454. addParam("keepOpen", "Slots to Keep Open", "number 1-15")
  455. addParam("careAboutResources", "Care About Resources","boolean")
  456. addParam("maxTries","Tries Before Bedrock", "number 1-9001")
  457. --Ore Quarry
  458. addParam("oreQuarry", "Ore Quarry", "boolean" )
  459. addParam("dumpCompareItems", "Dump Compare Items", "boolean", nil, oreQuarry) --Do not dump compare items if not oreQuarry
  460. addParam("extraDropItems", "", "force", nil, oreQuarry) --Prompt for extra dropItems
  461. addParam("extraDumpItems", "", "force", nil, oreQuarry, "extraDropItems") --changed to Dump
  462.  
  463. --Manual Position
  464. if tArgs["-manualpos"] then --Gives current coordinates in xPos,zPos,yPos, facing
  465.   local a = tArgs["-manualpos"]
  466.   xPos, zPos, yPos, facing = tonumber(tArgs[a+1]) or xPos, tonumber(tArgs[a+2]) or zPos, tonumber(tArgs[a+3]) or yPos, tonumber(tArgs[a+4]) or facing
  467.   changedT.new("xPos",xPos); changedT.new("zPos",zPos); changedT.new("yPos",yPos); changedT.new("facing",facing)
  468.   restoreFoundSwitch = true --So it doesn't do beginning of quarry behavior
  469.   for i=0,4 do tArgs[a+i] = "" end --Get rid of this argument from future restores
  470. end
  471. if addParam("atChest", "Is at Chest", "force") then --This sets position to 0,1,1, facing forward, and queues the turtle to go back to proper row.
  472.   local neededLayer = math.floor((yPos+1)/3)*3-1 --Make it a proper layer, +- because mining rows are 2, 5, etc.
  473.   if neededLayer > 2 and neededLayer%3 ~= 2 then --If turtle was not on a proper mining layer
  474.     print("Last known pos was not in proper layer, restarting quarry")
  475.     sleep(4)
  476.     neededLayer = 2
  477.   end
  478.   xPos, zPos, yPos, facing, rowCheck, layersDone = 0,1,1, 0, true, math.ceil(neededLayer/3)
  479.   events = {{"goto",1,1,neededLayer, 0}}
  480. end
  481.  
  482.  
  483. local function saveProgress(extras) --Session persistence
  484. exclusions = { modem = true, }
  485. if doBackup then
  486. local toWrite = ""
  487. for a,b in pairs(getfenv(1)) do
  488.   if not exclusions[a] then
  489.       --print(a ,"   ", b, "   ", type(b)) --Debug
  490.     if type(b) == "string" then b = "\""..b.."\"" end
  491.     if type(b) == "table" then b = textutils.serialize(b) end
  492.     if type(b) ~= "function" then
  493.       toWrite = toWrite..a.." = "..tostring(b).."\n"
  494.     end
  495.   end
  496. end
  497. toWrite = toWrite.."doCheckFuel = false\n" --It has already used fuel, so calculation unnecessary
  498. local file
  499. repeat
  500.   file = fs.open(saveFile,"w")
  501. until file
  502. file.write(toWrite)
  503. if type(extras) == "table" then
  504.   for a, b in pairs(extras) do
  505.     file.write(a.." = "..tostring(b).."\n")
  506.   end
  507. end
  508. if turtle.getFuelLevel() ~= math.huge then --Used for location comparing
  509.   file.write("fuelLevel = "..tostring(turtle.getFuelLevel()).."\n")
  510. end
  511. file.close()
  512. end
  513. end
  514.  
  515. local area = x*z
  516. local volume = x*y*z
  517. local lastHeight = y%3
  518. layers = math.ceil(y/3)
  519. local yMult = layers --This is basically a smart y/3 for movement
  520. local moveVolume = (area * yMult) --Kept for display percent
  521. --Calculating Needed Fuel--
  522. do --Because many local variables unneeded elsewhere
  523.   local changeYFuel = 2*(y + startDown)
  524.   local dropOffSupplies = 2*(x + z + y + startDown) --Assumes turtle as far away as possible, and coming back
  525.   local frequency = math.ceil(((moveVolume/(64*(15-uniqueExtras) + uniqueExtras)) ) ) --This is complicated: volume / inventory space of turtle, defined as 64*full stacks + 1 * unique stacks.
  526.                                                                                      --max of 15 full stacks because once one item is picked up, slot is "full". Ceil to count for initial back and forth
  527.   if enderChestEnabled then frequency = 0 end --Never goes back to start
  528.   neededFuel = moveVolume + changeYFuel + (frequency * dropOffSupplies) + ((x + z) * layers) --x + z *layers because turtle has to come back from far corner every layer
  529.   neededFuel = neededFuel + fuelTable[fuelSafety] --For safety
  530. end
  531.  
  532. if turtle.getFuelLimit and neededFuel+checkFuel() > turtle.getFuelLimit() then--Checks for if refueling goes over turtle fuel limit
  533.   if not doRefuel then
  534.     screen()
  535.     print("Turtle cannot hold enough fuel\n")
  536.     print("Options: \n1. Select a smaller size (press q) \n2. Enable Mid-Run Refueling (any other key)")
  537.     if ({os.pullEvent("char")})[2] == "q" then
  538.       screen(); print("Okay"); error("",0)
  539.     else
  540.       doRefuel = true
  541.     end
  542.   end
  543.   neededFuel = turtle.getFuelLimit()-checkFuel()-1
  544. end
  545.    
  546.    
  547. --Getting Fuel
  548. local hasRefueled --This is for oreQuarry prompting
  549. if doCheckFuel and checkFuel() < neededFuel then
  550.   hasRefueled = true
  551.   print("Not enough fuel")
  552.   print("Current: ",checkFuel()," Needed: ",neededFuel)
  553.   print("Starting SmartFuel...")
  554.   sleep(2) --So they can read everything.
  555.   term.clear()
  556.   local oneFuel, neededFuelItems
  557.   local currSlot = 0
  558.   local function output(text, x, y) --For displaying fuel
  559.     local currX, currY = term.getCursorPos()
  560.     term.setCursorPos(x,y)
  561.     term.clearLine()
  562.     term.write(text)
  563.     term.setCursorPos(currX,currY)
  564.     end
  565.   local function roundTo(num, target) --For stacks of fuel
  566.     if num >= target then return target elseif num < 0 then return 0 else return num end
  567.   end
  568.   local function updateScreen()
  569.     output("Welcome to SmartFuel! Now Refueling...", 1,1)
  570.     output("Currently taking fuel from slot "..currSlot,1,2)
  571.     output("Current single fuel: "..tostring(oneFuel or 0),1,3)
  572.     output("Current estimate of needed fuel: ",1,4)
  573.     output("Single Items: "..math.ceil(neededFuelItems or 0),4,5)
  574.     output("Stacks:       "..math.ceil((neededFuelItems or 0) / 64),4,6)
  575.     output("Needed Fuel: "..tostring(neededFuel),1,12)
  576.     output("Current Fuel: "..tostring(checkFuel()),1,13)
  577.   end
  578.   while checkFuel() <= neededFuel do
  579.     currSlot = currSlot + 1
  580.     select(currSlot)
  581.     if currSlot ~= 1 and not turtle.refuel(0) then --If its not the first slot, and not fuel, go back to start
  582.       currSlot = 1; select(currSlot)
  583.     end
  584.     updateScreen()
  585.     while turtle.getItemCount(currSlot) == 0 do
  586.       sleep(1.5)
  587.     end
  588.     repeat
  589.       local previous = checkFuel()
  590.       turtle.refuel(1)
  591.       oneFuel = checkFuel() - previous
  592.       updateScreen()
  593.     until (oneFuel or 0) > 0 --Not an if to prevent errors if fuel taken out prematurely.
  594.     neededFuelItems = (neededFuel - checkFuel()) / oneFuel
  595.     turtle.refuel(math.ceil(roundTo(neededFuelItems, 64))) --Change because can only think about 64 at once.
  596.     if turtle.getItemCount(roundTo(currSlot + 1, 16)) == 0 then --Resets if no more fuel
  597.       currSlot = 0
  598.     end
  599.     neededFuelItems = (neededFuel - checkFuel()) / oneFuel
  600.   end
  601. end
  602. --Ender Chest Obtaining
  603. function promptEnderChest()
  604.   while turtle.getItemCount(enderChestSlot) ~= 1 do
  605.     screen(1,1)
  606.     print("You have decided to use an Ender Chest!")
  607.     print("Please place one Ender Chest in slot ",enderChestSlot)
  608.     sleep(1)
  609.   end
  610.   print("Ender Chest in slot ",enderChestSlot, " checks out")
  611. end
  612. if enderChestEnabled then
  613.     if restoreFoundSwitch and turtle.getItemCount(enderChestSlot) == 0 then --If the turtle was stopped while dropping off items.
  614.       select(enderChestSlot)
  615.       turtle.dig()
  616.       select(1)
  617.     end
  618.   promptEnderChest()
  619.   allowedItems[enderChestSlot] = 64
  620.   sleep(2)
  621. end
  622. --Setting which slots are marked as compare slots
  623. if oreQuarry then
  624.   if not restoreFoundSwitch then --We don't want to reset compare blocks every restart
  625.     local counter = 0
  626.     for i=1, 16 do if turtle.getItemCount(i) > 0 and i ~= enderChestSlot then counter = counter+1 end end --If the slot has items, but isn't enderChest slot if it is enabled
  627.  
  628.     screen(1,1)
  629.     print("You have selected an Ore Quarry!")
  630.     if counter == 0 or hasRefueled then --If there are no compare slots, or the turtle has refueled, and probably has fuel in inventory
  631.       print("Please place your compare blocks in the first slots\n")
  632.      
  633.       print("Press Enter when done")
  634.       repeat until ({os.pullEvent("key")})[2] == 28 --Should wait for enter key to be pressed
  635.     else
  636.       print("Registering slots as compare slots")
  637.       sleep(1)
  638.     end
  639.     for i=1, 16 do
  640.       if turtle.getItemCount(i) > 0 then
  641.         if i ~= enderChestSlot then
  642.           table.insert(compareSlots, i) --Compare slots are ones compared to while mining. Conditions are because we Don't want to compare to enderChest
  643.           allowedItems[i] = 1 --Blacklist is for dropping off items. The number is maximum items allowed in slot when dropping off
  644.           dumpSlots[i] = true --We also want to ignore all excess of these items, like dirt
  645.         end
  646.       end
  647.     end
  648.     if extraDropItems then
  649.       screen(1,1)
  650.       print("Put in extra drop items now\n")
  651.       print("Press Enter when done")
  652.       repeat until ({os.pullEvent("key")})[2] == 28 --Should wait for enter key to be pressed
  653.       for i=1,16 do
  654.         if not dumpSlots[i] and turtle.getItemCount(i) > 0 then --I don't want to modify from above, so I check it hasn't been assigned.
  655.           dumpSlots[i] = true
  656.           allowedItems[i] = 1
  657.         end
  658.       end
  659.     end
  660.     --This is could go very wrong if this isn't here
  661.     if #compareSlots >= 16-keepOpen then screen(1,1); error("You have more quarry compare items than keep open slots, the turtle will continuously come back to start. Please fix.",0) end
  662.   end
  663.   local counter = 0
  664.   for a, b in pairs(compareSlots) do if  turtle.getItemCount(b) > 0 then counter = counter + 1 end end
  665.   if counter == 0 then
  666.     screen(1,1)
  667.     print("You have an ore quarry without any compare slots. Continue? y/n")
  668.     if ({os.pullEvent("char")})[2] ~= "y" then error("",0) end
  669.   end
  670. else
  671.   dumpCompareItems = false --If not an ore quarry, this should definitely be false
  672.   if enderChestSlot == 1 then
  673.     dumpSlots[2] = true
  674.   else
  675.     dumpSlots[1] = true
  676.   end
  677. end
  678.  
  679. --Initial Rednet Handshake
  680. if rednetEnabled then
  681.   screen(1,1)
  682.   print("Rednet is Enabled")
  683.   print("The Channel to open is "..channels.send)
  684.   if peripheral.find then
  685.     modem = peripheral.find("modem")
  686.   else
  687.     modem = peripheral.wrap("right")
  688.   end
  689.   modem.open(channels.receive)
  690.   local i = 0
  691.     repeat
  692.       local id = os.startTimer(3)
  693.       i=i+1
  694.       print("Sending Initial Message "..i)
  695.       modem.transmit(channels.send, channels.receive, channels.message)
  696.       local message
  697.       repeat
  698.         local event, idCheck, channel,_,locMessage, distance = os.pullEvent()
  699.         message = locMessage
  700.       until (event == "timer" and idCheck == id) or (event == "modem_message" and channel == channels.receive and message == channels.confirm)
  701.     until message == channels.confirm
  702.   connected = true
  703.   print("Connection Confirmed!")
  704.   sleep(1.5)
  705. end
  706. function biometrics(isAtBedrock)
  707.   if not rednetEnabled then return end --This function won't work if rednet not enabled :P
  708.   local toSend = { label = os.getComputerLabel() or "No Label", id = os.getComputerID(),
  709.     percent = percent, relxPos = relxPos, zPos = zPos, xPos = xPos, yPos = yPos,
  710.     layersDone = layersDone, x = x, z = z, layers = layers,
  711.     openSlots = getNumOpenSlots(), mined = mined, moved = moved,
  712.     chestFull = chestFull, isAtChest = (xPos == 0 and yPos == 1 and zPos == 1),
  713.     isGoingToNextLayer = (gotoDest == "layerStart"), foundBedrock = foundBedrock,
  714.     fuel = turtle.getFuelLevel(), volume = volume,
  715.     }
  716.   modem.transmit(channels.send, channels.receive, textutils.serialize(toSend))
  717.   id = os.startTimer(0.1)
  718.   local event, message
  719.   repeat
  720.     local locEvent, idCheck, confirm, _, locMessage, distance = os.pullEvent()
  721.     event, message = locEvent, locMessage or ""
  722.   until (event == "timer" and idCheck == id) or (event == "modem_message" and confirm == channels.receive)
  723.   if event == "modem_message" then connected = true else connected = false end
  724.   message = message:lower()
  725.   if message == "stop" then error("Rednet said to stop...",0) end
  726.   if message == "return" then
  727.     endingProcedure()
  728.     error('Rednet said go back to start...',0)
  729.   end
  730.   if message == "drop" then
  731.     dropOff()
  732.   end
  733.   if message == "pause" then
  734.     print("\nTurtle is paused. Send 'resume' or press any character to resume")
  735.     repeat
  736.       local event, idCheck, confirm, _, message, distance = os.pullEvent()
  737.     until (event == "modem_message" and confirm == channels.receive and message == "resume") or (event == "char")
  738.   end
  739.  
  740. end
  741. --Showing changes to settings
  742. screen(1,1)
  743. print("Your selected settings:")
  744. if #changedT == 0 then
  745. print("Completely Default")
  746. else
  747. for i=1, #changedT do
  748. print(changedT[i][1],": ",changedT[i][2]) --Name and Value
  749. end
  750. end
  751. print("\nStarting in 3"); sleep(1); print("2"); sleep(1); print("1"); sleep(1.5) --Dramatic pause at end
  752.  
  753.  
  754.  
  755. ----------------------------------------------------------------
  756. --Define ALL THE FUNCTIONS
  757. --Event System Functions
  758. function eventAddAt(pos, ...)
  759.   return table.insert(events,pos, {...}) or true
  760. end
  761. function eventAdd(...) --Just a wrapper
  762.   return eventAddAt(1, ...)
  763. end
  764. function eventGet(pos)
  765.   return events[tonumber(pos) or #events]
  766. end
  767. function eventPop(pos)
  768.   return table.remove(events,tonumber(pos) or #events) or false --This will return value popped, tonumber returns nil if fail, so default to end
  769. end
  770. function eventRun(value, ...)
  771.   local argsList = {...}
  772.   if type(value) == "string" then
  773.     if value:sub(-1) ~= ")" then --So supports both "up()" and "up"
  774.       value = value .. "("
  775.       for a, b in pairs(argsList) do --Appending arguments
  776.         local toAppend
  777.         if type(b) == "table" then toAppend = textutils.serialize(b)
  778.         elseif type(b) == "string" then toAppend = "\""..tostring(b).."\"" --They weren't getting strings around them
  779.         else toAppend = tostring(b) end
  780.         value = value .. (toAppend or "true") .. ", "
  781.       end
  782.       if value:sub(-1) ~= "(" then --If no args, do not want to cut off
  783.         value = value:sub(1,-3)..""
  784.       end
  785.       value = value .. ")"
  786.     end
  787.     --print(value) --Debug
  788.     local func = loadstring(value)
  789.     setfenv(func, getfenv(1))
  790.     return func()
  791.   end
  792. end
  793. function eventClear(pos)
  794.   if pos then events[pos] = nil else events = {} end
  795. end  
  796. function runAllEvents()
  797.   while #events > 0 do
  798.     local toRun = eventGet()
  799.     --print(toRun[1]) --Debug
  800.     eventRun(unpack(toRun))
  801.     eventPop()
  802.   end
  803. end
  804.  
  805. --Display Related Functions
  806. function display() --This is just the last screen that displays at the end
  807.   screen(1,1)
  808.   print("Total Blocks Mined: "..mined)
  809.   print("Current Fuel Level: "..turtle.getFuelLevel())
  810.   print("Cobble: "..totals.cobble)
  811.   print("Usable Fuel: "..totals.fuel)
  812.   print("Other: "..totals.other)
  813.   if rednetEnabled then
  814.     print("")
  815.     print("Sent Stop Message")
  816.     local finalTable = {mined = mined, cobble = totals.cobble, fuelblocks = totals.fuel,
  817.         other = totals.other, fuel = checkFuel() }
  818.     modem.transmit(channels.send,channels.receive,"stop")
  819.     sleep(0.5)
  820.     modem.transmit(channels.send,channels.receive,textutils.serialize(finalTable))
  821.     modem.close(channels.receive)
  822.   end
  823.   if doBackup then fs.delete(saveFile) end
  824. end
  825. function updateDisplay() --Runs in Mine(), display information to the screen in a certain place
  826. screen(1,1)
  827. print("Blocks Mined")
  828. print(mined)
  829. print("Percent Complete")
  830. print(percent.."%")
  831. print("Fuel")
  832. print(checkFuel())
  833.   -- screen(1,1)
  834.   -- print("Xpos: ")
  835.   -- print(xPos)
  836.   -- print("RelXPos: ")
  837.   -- print(relxPos)
  838.   -- print("Z Pos: ")
  839.   -- print(zPos)
  840.   -- print("Y pos: ")
  841.   -- print(yPos)
  842. if rednetEnabled then
  843. screenLine(1,7)
  844. print("Connected: "..tostring(connected))
  845. end
  846. end
  847. --Utility functions
  848. function logMiningRun(textExtension, extras) --Logging mining runs
  849.   if not logging then return end
  850.   local number, name = 0
  851.   if not fs.isDir(logFolder) then
  852.     fs.delete(logFolder)
  853.     fs.makeDir(logFolder)
  854.   end
  855.   repeat
  856.     number = number + 1 --Number will be at least 2
  857.     name = logFolder.."/Quarry_Log_"..tostring(number)..(textExtension or "")
  858.   until not fs.exists(name)
  859.   local handle = fs.open(name,"w")
  860.   local function write(...)
  861.     for a, b in ipairs({...}) do
  862.       handle.write(tostring(b))
  863.     end
  864.     handle.write("\n")
  865.   end
  866.   local function boolToText(bool) if bool then return "Yes" else return "No" end end
  867.   write("Welcome to the Quarry Logs!")
  868.   write("Entry Number: ",number)
  869.   write("Quarry Version: ",VERSION)
  870.   write("Dimensions (X Z Y): ",x," ",z," ", y)
  871.   write("Blocks Mined: ", mined)
  872.   write("  Cobble: ", totals.cobble)
  873.   write("  Usable Fuel: ", totals.fuel)
  874.   write("  Other: ",totals.other)
  875.   write("Total Fuel Used: ",  (originalFuel or (neededFuel + checkFuel()))- checkFuel()) --Protect against errors with some precision
  876.   write("Expected Fuel Use: ", neededFuel)
  877.   write("Days to complete mining run: ",os.day()-originalDay)
  878.   write("Day Started: ", originalDay)
  879.   write("Number of times resumed: ", numResumed)
  880.   write("Was an ore quarry? ",boolToText(oreQuarry))
  881.   write("Was inverted? ",boolToText(invert))
  882.   write("Was using rednet? ",boolToText(rednetEnabled))
  883.   write("Chest was on the ",dropSide," side")
  884.   if startDown > 0 then write("Started ",startDown," blocks down") end
  885.   handle.close()
  886. end
  887. --Inventory related functions
  888. function isFull(slots) --Checks if there are more than "slots" used inventory slots.
  889.   slots = slots or 16
  890.   local numUsed = 0
  891.   sleep(0)
  892.   for i=1, 16 do
  893.     if turtle.getItemCount(i) > 0 then numUsed = numUsed + 1 end
  894.   end
  895.   if numUsed > slots then
  896.     return true
  897.   end
  898.   return false
  899. end
  900. function countUsedSlots() --Returns number of slots with items in them, as well as a table of item counts
  901.   local toRet, toRetTab = 0, {}
  902.   for i=1, 16 do
  903.     local a = turtle.getItemCount(i)
  904.     if a > 0 then toRet = toRet + 1 end
  905.     table.insert(toRetTab, a)
  906.   end
  907.   return toRet, toRetTab
  908. end
  909. function getSlotsTable() --Just get the table from above
  910.   local _, toRet = countUsedSlots()
  911.   return toRet
  912. end
  913. function getChangedSlots(tab1, tab2) --Returns a table of changed slots. Format is {slotNumber, numberChanged}
  914.   local toRet = {}
  915.   for i=1, min(#tab1, #tab2) do
  916.     diff = math.abs(tab2[i]-tab1[i])
  917.     if diff > 0 then
  918.       table.insert(toRet, {i, diff})
  919.     end
  920.   end
  921.   return toRet
  922. end
  923. function getFirstChanged(tab1, tab2) --Just a wrapper. Probably not needed
  924.   local a = getChangedSlots(tab1,tab2)
  925.   return a[1][1]
  926. end
  927.  
  928. function getRep(which, list) --Gets a representative slot of a type. Expectation is a sequential table of types
  929.   for a,b in pairs(list) do
  930.     if b == which then return a end
  931.   end
  932.   return false
  933. end
  934. function assignTypes(types, count) --The parameters allow a preexisting table to be used, like a table from the original compareSlots...
  935.   types, count = types or {1}, count or 1 --Table of types and current highest type
  936.   for i=1, 16 do
  937.     if turtle.getItemCount(i) > 0 then
  938.       select(i)
  939.       for k=1, count do
  940.         if turtle.compareTo(getRep(k, types)) then types[i] = k end
  941.       end
  942.       if not types[i] then
  943.         count = count + 1
  944.         types[i] = count
  945.       end
  946.      
  947.     end
  948.   end
  949.   select(1)
  950.   return types, count
  951. end
  952. function getTableOfType(which, list) --Returns a table of all the slots of which type
  953.   local toRet = {}
  954.   for a, b in pairs(list) do
  955.     if b == which then
  956.       table.insert(toRet, a)
  957.     end
  958.   end
  959.   return toRet
  960. end
  961.  
  962. --This is so the turtle will properly get types, otherwise getRep of a type might not be a dumpSlot, even though it should be.
  963. if not restoreFoundSwitch then --We only want this to happen once
  964.   if oreQuarry then --If its not ore quarry, this screws up type assigning
  965.     initialTypes, initialCount = assignTypes()
  966.   else
  967.     initialTypes, initialCount = {1}, 1
  968.   end
  969. end
  970.  
  971. function count(add) --Done any time inventory dropped and at end, true=add, false=nothing, nil=subtract
  972.   local mod = -1
  973.   if add then mod = 1 end
  974.   if add == false then mod = 0 end
  975.   slot = {}        --1: Filler 2: Fuel 3:Other --[1] is type, [2] is number
  976.   for i=1, 16 do  
  977.     slot[i] = {}
  978.     slot[i][2] = turtle.getItemCount(i)
  979.   end
  980.  
  981.   local function iterate(toSet , rawTypes, set)
  982.     for _, a in pairs(getTableOfType(toSet, rawTypes)) do --Get all slots matching type
  983.       slot[a][1] = set --Set official type to "set"
  984.     end
  985.   end
  986.  
  987.   --This assigns "dumb" types to all slots based on comparing, then based on knowledge of dump type slots, changes all slots matching a dump type to one. Otherwise, if the slot contains fuel, it is 2, else 3
  988.   local rawTypes, numTypes = assignTypes(copyTable(initialTypes), initialCount) --This gets increasingly numbered types, copyTable because assignTypes will modify it
  989.  
  990.   for i=1, numTypes do
  991.     if (select(getRep(i, rawTypes)) or true) and turtle.refuel(0) then --Selects the rep slot, checks if it is fuel
  992.       iterate(i, rawTypes, 2) --This type is fuel
  993.     elseif dumpSlots[getRep(i,initialTypes)] then --If the rep of this slot is a dump item. This is initial types so that the rep is in dump slots
  994.       iterate(i, rawTypes, 1) --This type is cobble/filler
  995.     else
  996.       iterate(i, rawTypes, 3) --This type is other
  997.     end
  998.   end
  999.    
  1000.     for i=1,16 do
  1001.       if i == enderChestSlot then --Do nothing!
  1002.       elseif slot[i][1] == 1 then totals.cobble = totals.cobble + (slot[i][2] * mod)
  1003.       elseif slot[i][1] == 2 then totals.fuel = totals.fuel + (slot[i][2] * mod)
  1004.       elseif slot[i][1] == 3 then totals.other = totals.other + (slot[i][2] * mod) end
  1005.     end
  1006.  
  1007.   select(1)
  1008. end
  1009.  
  1010. --Mining functions
  1011. function dig(doAdd, func)
  1012.   if doAdd == nil then doAdd = true end
  1013.   func = func or turtle.dig
  1014.   if func() then
  1015.     if doAdd then
  1016.       mined = mined + 1
  1017.     end
  1018.     return true
  1019.   end
  1020.   return false
  1021. end
  1022.  
  1023.  
  1024.  
  1025. function digUp(doAdd)--Regular functions :) I switch definitions for optimization (I think)
  1026.   return dig(doAdd, turtle.digUp)
  1027. end
  1028. function digDown(doAdd)
  1029.   return dig(doAdd, turtle.digDown)
  1030. end
  1031. if inverted then --If inverted, switch the options
  1032.   digUp, digDown = digDown, digUp
  1033. end
  1034.  
  1035. function smartDig(digUp, digDown) --This function is used only in mine when oreQuarry
  1036.   local blockAbove, blockBelow = digUp and turtle.detectUp(), digDown and turtle.detectDown() --These control whether or not the turtle digs
  1037.   local index = 1
  1038.   for i=1, #compareSlots do
  1039.     if not (blockAbove or blockBelow) then break end --We don't want to go selecting if there is nothing to dig
  1040.     index = i --To access out of scope
  1041.     select(compareSlots[i])
  1042.     if blockAbove and turtle.compareUp() then blockAbove = false end
  1043.     if blockBelow and turtle.compareDown() then blockBelow = false end
  1044.   end
  1045.   table.insert(compareSlots, 1, table.remove(compareSlots, index)) --This is so the last selected slot is the first slot checked, saving a turtle.select call
  1046.   if blockAbove then dig(true, turtle.digUp) end
  1047.   if blockBelow then dig(true, turtle.digDown) end
  1048. end
  1049.  
  1050. function setRowCheckFromPos()
  1051.   rowCheck = (zPos % 2 == 1) --It will turn right at odd rows
  1052. end
  1053. function relxCalc()
  1054.   if rowCheck then relxPos = xPos else relxPos = (x-xPos)+1 end
  1055. end
  1056. function forward(doAdd)
  1057.   if doAdd == nil then doAdd = true end
  1058.   if turtle.forward() then
  1059.     if doAdd then
  1060.       moved = moved + 1
  1061.     end
  1062.     if facing == 0 then
  1063.       xPos = xPos + 1
  1064.     elseif facing == 1 then
  1065.       zPos = zPos + 1
  1066.     elseif facing == 2 then
  1067.       xPos = xPos - 1
  1068.     elseif facing == 3 then
  1069.       zPos = zPos - 1
  1070.     else
  1071.       error("Function forward, facing should be 0 - 3, got "..tostring(facing),2)
  1072.     end
  1073.     relxCalc()
  1074.     return true
  1075.   end
  1076.   return false
  1077. end
  1078. function up(sneak)
  1079.   sneak = sneak or 1
  1080.   if inverted and sneak == 1 then
  1081.     down(-1)
  1082.   else
  1083.     while not turtle.up() do --Absolute dig, not relative
  1084.       if not dig(true, turtle.digUp) then
  1085.         attackUp()
  1086.         sleep(0.5)
  1087.       end
  1088.     end
  1089.     yPos = yPos - sneak --Oh! I feel so clever
  1090.   end                   --This works because inverted :)
  1091.   saveProgress()
  1092.   biometrics()
  1093. end
  1094. function down(sneak)
  1095.   sneak = sneak or 1
  1096.   local count = 0
  1097.   if inverted and sneak == 1 then
  1098.     up(-1)
  1099.   else
  1100.     while not turtle.down() do
  1101.       count = count + 1
  1102.       if not dig(true, turtle.digDown) then --This is absolute dig down, not relative
  1103.         attackDown()
  1104.         sleep(0.2)
  1105.       end
  1106.       if count > 20 then bedrock() end
  1107.     end
  1108.     yPos = yPos + sneak
  1109.   end
  1110.   saveProgress()
  1111.   biometrics()
  1112. end
  1113. function right(num)
  1114.   num = num or 1
  1115.   for i=1, num do facing = coterminal(facing+1); saveProgress(); turtle.turnRight() end
  1116. end
  1117. function left(num)
  1118.   num = num or 1
  1119.   for i=1, num do facing = coterminal(facing-1); saveProgress(); turtle.turnLeft() end
  1120. end
  1121. function attack(doAdd, func)
  1122.   doAdd = doAdd or true
  1123.   func = func or turtle.attack
  1124.   if func() then
  1125.     if doAdd then
  1126.       attacked = attacked + 1
  1127.     end
  1128.     return true
  1129.   end
  1130.   return false
  1131. end
  1132. function attackUp(doAdd)
  1133.   if inverted then
  1134.     return attack(doAdd, turtle.attackDown)
  1135.   else
  1136.     return attack(doAdd, turtle.attackUp)
  1137.   end
  1138. end
  1139. function attackDown(doAdd)
  1140.   if inverted then
  1141.     return attack(doAdd, turtle.attackUp)
  1142.   else
  1143.     return attack(doAdd, turtle.attackDown)
  1144.   end
  1145. end
  1146.  
  1147.  
  1148. function mine(doDigDown, doDigUp, outOfPath,doCheckInv) -- Basic Move Forward
  1149.   if doCheckInv == nil then doCheckInv = true end
  1150.   if doDigDown == nil then doDigDown = true end
  1151.   if doDigUp == nil then doDigUp = true end
  1152.   if outOfPath == nil then outOfPath = false end
  1153.   isInPath = (not outOfPath) --For rednet
  1154.   if inverted then
  1155.     doDigUp, doDigDown = doDigDown, doDigUp --Just Switch the two if inverted
  1156.   end
  1157.   if not outOfPath and (checkFuel() <= xPos + zPos + yPos + 5) then --If the turtle can just barely get back to the start, we need to get it there. We don't want this to activate coming back though...
  1158.     local continueEvac = true --This turns false if more fuel is acquired
  1159.     if doRefuel then --Attempt an emergency refueling
  1160.       screen()
  1161.       print("Attempting an emergency refuel")
  1162.       print("Fuel Level:    ",checkFuel())
  1163.       print("Distance Back: ",(xPos+zPos+yPos+1))
  1164.       print("Categorizing Items")
  1165.       count(false) --Do not add count, but categorize
  1166.       local fuelSwitch, initialFuel = false, checkFuel() --Fuel switch so we don't go over limit (in emergency...)
  1167.       print("Going through available fuel slots")
  1168.       for i=1, 16 do
  1169.         if fuelSwitch then break end
  1170.         if turtle.getItemCount(i) > 0 and slot[i][1] == 2 then --If there are items and type 2 (fuel)
  1171.           turtle.select(i)
  1172.           fuelSwitch = midRunRefuel(i) --See above "function drop" for usage
  1173.         end
  1174.       end
  1175.       turtle.select(1) --Cleanup
  1176.       print("Done fueling")
  1177.       if checkFuel() > initialFuel then
  1178.         continueEvac = false
  1179.         print("Evac Aborted")
  1180.       else
  1181.         print("Evac is a go, returning to base")
  1182.         sleep(1.5) --Pause for reading
  1183.       end
  1184.     end
  1185.     if continueEvac then
  1186.       eventClear() --Clear any annoying events for evac
  1187.       endingProcedure("Turtle ran low on fuel so was brought back to start for you :)\n\nTo resume where you left off, use '-startDown "..tostring(y-2).."' when you start") --Finish the program
  1188.     end
  1189.   end
  1190.   local count = 0
  1191.   while not forward(not outOfPath) do
  1192.     sleep(0) --Calls coroutine.yield to prevent errors
  1193.     count = count + 1
  1194.     if not dig() then
  1195.       attack()
  1196.     end
  1197.     if count > 10 then
  1198.       attack()
  1199.       sleep(0.2)
  1200.     end
  1201.     if count > maxTries then
  1202.       if turtle.getFuelLevel() == 0 then --Don't worry about inf fuel because I modified this function
  1203.         saveProgress({doCheckFuel = true})
  1204.         error("No more fuel",0)
  1205.       elseif yPos > (startY-7) and turtle.detect() then --If it is near bedrock
  1206.         bedrock()
  1207.       else --Otherwise just sleep for a bit to avoid sheeps
  1208.         sleep(1)
  1209.       end
  1210.     end
  1211.   end
  1212.   checkSanity() --Not kidding... This is necessary
  1213.   saveProgress(tab)
  1214.   if not oreQuarry then --The digging up and down part
  1215.     if doDigUp then
  1216.       while turtle.detectUp() do
  1217.         sleep(0) --Calls coroutine.yield
  1218.         if not dig(true,turtle.digUp) then --This needs to be an absolute, because we are switching doDigUp/Down
  1219.           if not attackUp() then
  1220.             if yPos > (startY-7) then bedrock() end --Checking for bedrock, but respecting user wishes
  1221.           end
  1222.         end
  1223.       end
  1224.     end
  1225.     if doDigDown then
  1226.      dig(true,turtle.digDown) --This needs to be absolute as well
  1227.     end
  1228.   else
  1229.     smartDig(doDigUp, doDigDown)
  1230.   end
  1231.   percent = math.ceil(moved/moveVolume*100)
  1232.   updateDisplay()
  1233.   if doCheckInv and careAboutResources then
  1234.     if isFull(16-keepOpen) then dropOff() end
  1235.   end
  1236.   biometrics()
  1237. end
  1238. --Insanity Checking
  1239. function checkSanity()
  1240.   if not isInPath then --I don't really care if its not in the path.
  1241.     return true
  1242.   end
  1243.   if not (facing == 0 or facing == 2) and #events == 0 then --If mining and not facing proper direction and not in a turn
  1244.     turnTo(0)
  1245.     rowCheck = true
  1246.   end
  1247.   if xPos < 0 or xPos > x or zPos < 0 or zPos > z or yPos < 0 then
  1248.     saveProgress()
  1249.     print("I have gone outside boundaries, attempting to fix (maybe)")
  1250.     if xPos > x then goto(x, zPos, yPos, 2) end --I could do this with some fancy math, but this is much easier
  1251.     if xPos < 0 then goto(1, zPos, yPos, 0) end
  1252.     if zPos > z then goto(xPos, z, yPos, 3) end
  1253.     if zPos < 0 then goto(xPos, 1, yPos, 1) end
  1254.     setRowCheckFromPos() --Row check right (maybe left later)
  1255.     relxCalc() --Get relxPos properly
  1256.     eventClear()
  1257.    
  1258.     --[[
  1259.     print("Oops. Detected that quarry was outside of predefined boundaries.")
  1260.     print("Please go to my forum thread and report this with a short description of what happened")
  1261.     print("If you could also run \"pastebin put Civil_Quarry_Restore\" and give me that code it would be great")
  1262.     error("",0)]]
  1263.   end
  1264. end
  1265.  
  1266. local function fromBoolean(input) --Like a calculator
  1267. if input then return 1 end
  1268. return 0
  1269. end
  1270. local function multBoolean(first,second) --Boolean multiplication
  1271. return (fromBoolean(first) * fromBoolean(second)) == 1
  1272. end
  1273. function coterminal(num, limit) --I knew this would come in handy :D
  1274. limit = limit or 4 --This is for facing
  1275. return math.abs((limit*fromBoolean(num < 0))-(math.abs(num)%limit))
  1276. end
  1277. if tArgs["-manualpos"] then
  1278.   facing = coterminal(facing) --Done to improve support for "-manualPos"
  1279.   if facing == 0 then rowCheck = true elseif facing == 2 then rowCheck = false end --Ditto
  1280.   relxCalc() --Ditto
  1281. end
  1282.  
  1283. --Direction: Front = 0, Right = 1, Back = 2, Left = 3
  1284. function turnTo(num)
  1285.   num = num or facing
  1286.   num = coterminal(num) --Prevent errors
  1287.   local turnRight = true
  1288.   if facing-num == 1 or facing-num == -3 then turnRight = false end --0 - 1 = -3, 1 - 0 = 1, 2 - 1 = 1
  1289.   while facing ~= num do          --The above is used to smartly turn
  1290.     if turnRight then
  1291.       right()
  1292.     else
  1293.       left()
  1294.     end
  1295.   end
  1296. end
  1297. function goto(x,z,y, toFace, destination)
  1298.   --Will first go to desired z pos, then x pos, y pos varies
  1299.   x = x or 1; y = y or 1; z = z or 1; toFace = toFace or facing
  1300.   gotoDest = destination or "" --This is used by biometrics
  1301.   --Possible destinations: layerStart, quarryStart
  1302.   if yPos > y then --Will go up first if below position
  1303.     while yPos~=y do up() end
  1304.   end
  1305.   if zPos > z then
  1306.     turnTo(3)
  1307.   elseif zPos < z then
  1308.     turnTo(1)
  1309.   end
  1310.   while zPos ~= z do mine(false,false,true,false) end
  1311.   if xPos > x then
  1312.     turnTo(2)
  1313.   elseif xPos < x then
  1314.     turnTo(0)
  1315.   end
  1316.   while xPos ~= x do mine(false,false,true,false) end
  1317.   if yPos < y then --Will go down after if above position
  1318.     while yPos~=y do down() end
  1319.   end
  1320.   turnTo(toFace)
  1321.   saveProgress()
  1322.   gotoDest = ""
  1323. end
  1324. function getNumOpenSlots()
  1325.   local toRet = 0
  1326.   for i=1, 16 do
  1327.     if turtle.getItemCount(i) == 0 then
  1328.       toRet = toRet + 1
  1329.     end
  1330.   end
  1331.   return toRet
  1332. end
  1333.  
  1334. --Ideas: Bring in inventory change-checking functions, count blocks that have been put in, so it will wait until all blocks have been put in.
  1335. local function waitDrop(slot, allowed, whereDrop) --This will just drop, but wait if it can't
  1336.   allowed = allowed or 0
  1337.   while turtle.getItemCount(slot) > allowed do --No more half items stuck in slot!
  1338.     local tries = 1
  1339.     while not whereDrop(turtle.getItemCount(slot)-allowed) do --Drop off only the amount needed
  1340.       screen(1,1)
  1341.       print("Chest Full, Try "..tries)
  1342.       chestFull = true
  1343.       biometrics()--To send that the chest is full
  1344.       tries = tries + 1
  1345.       sleep(2)
  1346.     end
  1347.     chestFull = false
  1348.   end
  1349. end
  1350.  
  1351. function midRunRefuel(i)
  1352.   local numToRefuel = turtle.getItemCount(i)-allowedItems[i]
  1353.   if checkFuel() >= turtle.getFuelLimit() then return true end --If it doesn't need fuel, then signal to not take more
  1354.   local firstCheck = checkFuel()
  1355.   if numToRefuel > 0 then turtle.refuel(1) end --This is so we can see how many fuel we need.
  1356.   local singleFuel
  1357.   if checkFuel() - firstCheck > 0 then singleFuel = checkFuel() - firstCheck else singleFuel = math.huge end --If fuel is 0, we want it to be huge so the below will result in 0 being taken
  1358.   --Refuel      The lesser of   max allowable or         remaining fuel space         /    either inf or a single fuel (which can be 0)
  1359.   turtle.refuel(math.min(numToRefuel-1, math.ceil((turtle.getFuelLimit()-checkFuel()) / singleFuel))) --The refueling part of the the doRefuel option
  1360.   return false --Turtle can still be fueled
  1361. end
  1362.  
  1363. function drop(side, final)
  1364.   side = sides[side] or "front"
  1365.   local dropFunc, detectFunc, dropFacing = turtle.drop, turtle.detect, facing+2
  1366.   if side == "top" then dropFunc, detectFunc = turtle.dropUp, turtle.detectUp end
  1367.   if side == "bottom" then dropFunc, detectFunc = turtle.dropDown, turtle.detectDown end
  1368.   if side == "right" then turnTo(1); dropFacing = 0 end
  1369.   if side == "left" then turnTo(3); dropFacing = 0 end
  1370.   local properFacing = facing --Capture the proper direction to be facing
  1371.  
  1372.   count(true) --Count number of items before drop. True means add. This is before chest detect, because could be final
  1373.  
  1374.   while not detectFunc() do
  1375.     if final then return end --If final, we don't need a chest to be placed, but there can be
  1376.     chestFull = true
  1377.     biometrics() --Let the user know there is a problem with chest
  1378.     screen(1,1) --Clear screen
  1379.     print("Waiting for chest placement on ",side," side (when facing quarry)")
  1380.     sleep(2)
  1381.   end
  1382.   chestFull = false
  1383.  
  1384.   local fuelSwitch = false --If doRefuel, this can switch so it won't overfuel
  1385.   for i=1,16 do
  1386.     --if final then allowedItems[i] = 0 end --0 items allowed in all slots if final ----It is already set to 1, so just remove comment if want change
  1387.     if turtle.getItemCount(i) > 0 then --Saves time, stops bugs
  1388.       if slot[i][1] == 1 and dumpCompareItems then turnTo(dropFacing) --Turn around to drop junk, not store it. dumpComapareItems is global config
  1389.       else turnTo(properFacing) --Turn back to proper position... or do nothing if already there
  1390.       end
  1391.       select(i)
  1392.       if doRefuel and slot[i][1] == 2 then --Intelligently refuels to fuel limit
  1393.         if not fuelSwitch then --Not in the conditional because we don't want to waitDrop excess fuel. Not a break so we can drop junk
  1394.           fuelSwitch = midRunRefuel(i)
  1395.         end
  1396.       else
  1397.         waitDrop(i, allowedItems[i], dropFunc)
  1398.       end
  1399.     end
  1400.   end
  1401.  
  1402.   if oreQuarry then count(nil) end--Subtract the items still there if oreQuarry
  1403.   resetDumpSlots() --So that slots gone aren't counted as dump slots next
  1404.  
  1405.   select(1) --For fanciness sake
  1406.  
  1407. end
  1408.  
  1409. function dropOff() --Not local because called in mine()
  1410.   local currX,currZ,currY,currFacing = xPos, zPos, yPos, facing
  1411.   if careAboutResources then
  1412.     if not enderChestEnabled then --Regularly
  1413.       eventAdd("goto", 1,1,currY,2) --Need this step for "-startDown"
  1414.       eventAdd("goto(0,1,1,2)")
  1415.       eventAdd("drop", dropSide,false)
  1416.       eventAdd("turnTo(0)")
  1417.       eventAdd("mine",false,false,true,false)
  1418.       eventAdd("goto(1,1,1, 0)")
  1419.       eventAdd("goto", 1, 1, currY, 0)
  1420.       eventAdd("goto", currX,currZ,currY,currFacing)
  1421.     else --If using an enderChest
  1422.       if turtle.getItemCount(enderChestSlot) ~= 1 then eventAdd("promptEnderChest()") end
  1423.       eventAdd("turnTo",currFacing-2)
  1424.       eventAdd("dig",false)
  1425.       eventAdd("select",enderChestSlot)
  1426.       eventAdd("turtle.place")
  1427.       eventAdd("drop","front",false)
  1428.       eventAdd("turnTo",currFacing-2)
  1429.       eventAdd("select", enderChestSlot)
  1430.       eventAdd("dig",false)
  1431.       eventAdd("turnTo",currFacing)
  1432.       eventAdd("select(1)")
  1433.     end
  1434.     runAllEvents()
  1435.     numDropOffs = numDropOffs + 1 --Analytics tracking
  1436.   end
  1437.   return true
  1438. end
  1439. function endingProcedure(endingMessage) --Used both at the end and in "biometrics"
  1440.   eventAdd("goto",1,1,yPos,2,"quarryStart") --Allows for startDown variable
  1441.   eventAdd("goto",0,1,1,2, "quarryStart") --Go back to base
  1442.   runAllEvents()
  1443.   --Output to a chest or sit there
  1444.   if enderChestEnabled then
  1445.     if dropSide == "right" then eventAdd("turnTo(1)") end --Turn to proper drop side
  1446.     if dropSide == "left" then eventAdd("turnTo(3)") end
  1447.     eventAdd("dig(false)") --This gets rid of a block in front of the turtle.
  1448.     eventAdd("select",enderChestSlot)
  1449.     eventAdd("turtle.place")
  1450.     eventAdd("select(1)")
  1451.   end
  1452.   eventAdd("drop",dropSide, true)
  1453.   eventAdd("turnTo(0)")
  1454.  
  1455.   --Display was moved above to be used in bedrock function
  1456.   eventAdd("display")
  1457.   --Log current mining run
  1458.   eventAdd("logMiningRun",logExtension)
  1459.   eventAdd("error",endingMessage or "",0)
  1460.   toQuit = true --I'll use this flag to clean up (legacy)
  1461.   runAllEvents()
  1462.   --Cleanup
  1463.   turtle.getFuelLevel = getFuel
  1464. end
  1465. function bedrock()
  1466.   foundBedrock = true --Let everyone know
  1467.   if rednetEnabled then biometrics() end
  1468.   if checkFuel() == 0 then error("No Fuel",0) end
  1469.   local origin = {x = xPos, y = yPos, z = zPos}
  1470.   print("Bedrock Detected")
  1471.   if turtle.detectUp() then
  1472.     print("Block Above")
  1473.     local var
  1474.     if facing == 0 then var = 2 elseif facing == 2 then var = 0 else error("Was facing left or right on bedrock") end
  1475.     goto(xPos,zPos,yPos,var)
  1476.     for i=1, relxPos do mine(false, false); end
  1477.   end
  1478.   eventClear() --Get rid of any excess events that may be run. Don't want that.
  1479.   endingProcedure()
  1480.   print("\nFound bedrock at these coordinates: ")
  1481.   print(origin.x," Was position in row\n",origin.z," Was row in layer\n",origin.y," Blocks down from start")
  1482.   error("",0)
  1483. end
  1484.  
  1485. function endOfRowTurn(startZ, wasFacing, mineFunctionTable)
  1486. local halfFacing = 1
  1487. local toFace = coterminal(wasFacing + 2) --Opposite side
  1488. if zPos == startZ then
  1489.   if facing ~= halfFacing then turnTo(halfFacing) end
  1490.   mine(unpack(mineFunctionTable or {}))
  1491. end
  1492. if facing ~= toFace then
  1493.   turnTo(toFace)
  1494. end
  1495. end
  1496.  
  1497.  
  1498. -------------------------------------------------------------------------------------
  1499. --Pre-Mining Stuff dealing with session persistence
  1500. runAllEvents()
  1501. if toQuit then error("",0) end --This means that it was stopped coming for its last drop
  1502.  
  1503. local doDigDown, doDigUp = (lastHeight ~= 1), (lastHeight == 0) --Used in lastHeight
  1504. if not restoreFoundSwitch then --Regularly
  1505.   --Check if it is a mining turtle
  1506.   if not isMiningTurtle then
  1507.     local a, b = turtle.dig()
  1508.     if a then mined = mined + 1; isMiningTurtle = true
  1509.     elseif b == "Nothing to dig with" then
  1510.       print("This is not a mining turtle. To make a mining turtle, craft me together with a diamond pickaxe")
  1511.       error("",0)
  1512.     end
  1513.   end
  1514.   mine(false,false,true) --Get into quarry by going forward one
  1515.   if gpsEnabled and not restoreFoundSwitch then --The initial locate is done in the arguments. This is so I can figure out what quadrant the turtle is in.
  1516.     gpsSecondPos = {gps.locate(gpsTimeout)} --Note: Does not run this if it has already been restarted.
  1517.   end
  1518.   for i = 1, startDown do
  1519.     eventAdd("down") --Add a bunch of down events to get to where it needs to be.
  1520.   end
  1521.   runAllEvents()
  1522.   if not(y == 1 or y == 2) then down() end --Go down. If y is one or two, it doesn't need to do this.
  1523. else --restore found
  1524.   if not(layersDone == layers and not doDigDown) then digDown() end
  1525.   if not(layersDone == layers and not doDigUp) then digUp() end  --Get blocks missed before stopped
  1526. end
  1527. --Mining Loops--------------------------------------------------------------------------
  1528. select(1)
  1529. while layersDone <= layers do -------------Height---------
  1530. local lastLayer = layersDone == layers --If this is the last layer
  1531. local secondToLastLayer = (layersDone + 1) == layers --This is a check for going down at the end of a layer.
  1532. moved = moved + 1 --To account for the first position in row as "moved"
  1533. if not(layersDone == layers and not doDigDown) then digDown() end --This is because it doesn't mine first block in layer
  1534. if not restoreFoundSwitch then rowCheck = true end
  1535. relxCalc()
  1536. while zPos <= z do -------------Width----------
  1537. while relxPos < x do ------------Length---------
  1538. mine(not lastLayer or (doDigDown and lastLayer), not lastLayer or (doDigUp and lastLayer)) --This will be the idiom that I use for the mine function
  1539. end ---------------Length End-------
  1540. if zPos ~= z then --If not on last row of section
  1541.   local func
  1542.   if rowCheck == true then --Switching to next row
  1543.   func = "right"; rowCheck = false; else func = false; rowCheck = true end --Which way to turn
  1544.     eventAdd("endOfRowTurn", zPos, facing , {not lastLayer or (doDigDown and lastLayer), not lastLayer or (doDigUp and lastLayer)}) --The table is passed to the mine function
  1545.     runAllEvents()
  1546. else break
  1547. end
  1548. end ---------------Width End--------
  1549. eventAdd("goto",1,1,yPos,0, "layerStart") --Goto start of layer
  1550. if not lastLayer then --If there is another layer
  1551.   for i=1, 2+fromBoolean(not(lastHeight~=0 and secondToLastLayer)) do eventAdd("down()") end --The fromBoolean stuff means that if lastheight is 1 and last and layer, will only go down two
  1552. end
  1553. eventAdd("setRowCheckFromPos")
  1554. eventAdd("relxCalc")
  1555. layersDone = layersDone + 1
  1556. restoreFoundSwitch = false --This is done so that rowCheck works properly upon restore
  1557. runAllEvents()
  1558. end ---------------Height End-------
  1559.  
  1560. endingProcedure() --This takes care of getting to start, dropping in chest, and displaying ending screen
RAW Paste Data