args = {...}

torchdistance = 5
torchcounter = 0
torchslot = 16

if args[1] == nil then
	write "how long do you want the tunnell:"
	long = tonumber(read())
else
	long = tonumber(args[1])
end



--FUNCTIONS--

function mine(poo)
  dig()
  goforward()
  digUp()
  turtle.digDown()
  turtle.turnLeft()
  dig()
  goforward()
  digUp()
  turtle.digDown()
  goback()
  turtle.turnRight()
  turtle.turnRight()
  dig()
  goforward()
  digUp()
  turtle.digDown()
  goback()
  if torchcounter == torchdistance then
    turtle.select(16)
    turtle.place()
    turtle.select(1)
    torchcounter = 0
  else
    torchcounter = torchcounter + 1
  end
  turtle.turnLeft()

  if turtle.getItemCount(15) > 0 then
    for o = poo,0,-1 do
      goback()
    end
    return true
  else return false
  end
end

function refuel(min)
  if turtle.getFuelLevel() < min then
    for l=1,16 do
      if turtle.getItemCount(l) > 0 then
        turtle.select(l)
        if turtle.refuel(1) then
          while turtle.getFuelLevel() < min and turtle.getItemCount(l) > 0 do
            turtle.refuel(1)
          end
        end
      end
      if turtle.getFuelLevel() > min then
        break
      end
	end
    if turtle.getFuelLevel() < min then
      print "insert fuel and press any key"
      ev,pa = os.pullEvent("key")
      refuel(min)
     end
  end
  min = nil
  turtle.select(1)
end

function digUp()
  repeat
    turtle.digUp()
    sleep(0.5)
  until not turtle.detectUp()
end

function dig()
  repeat
    turtle.dig()
    sleep(0.5)
  until not turtle.detect()
end

function goback()
  while not turtle.back() do end
end

function goforward()
  while not turtle.forward() do
    turtle.attack()
  end
end

function gotostart()
  refuel(long)
  for i = 0, long do
    goback()
  end
end
  
function info(counter)
  term.clear()
  term.setCursorPos(1,1)
  print("fuel: "..turtle.getFuelLevel())
  print("blocks to go: "..long - counter)
  print("blocks until torch placement: "..torchdistance - torchcounter)
  if turtle.getItemCount(16) < 1 then
    print("")
    print("place torches in slot 16!")
  end
end

-- MAIN --

for i = 0, long do
  refuel(10)
  info(i)
  if mine(i) == true then
    term.clear()
    term.setCursorPos(1,1)
    return print("INV FULL!   program terminated")
  end
  info(i)
end

gotostart()
term.clear()
term.setCursorPos(1,1)
print("DONE")