local function dig(up)
  while up and turtle.inspectUp() do
    turtle.digUp()
  end

  while turtle.inspect() do
    turtle.dig()
  end
end

local function forward()
  while not turtle.forward() do
    dig(false)
  end
end

local function line(length)
  for _=2,length do
    forward()
  end
end

local function fuelCheck(lineWidth)
  return turtle.getFuelLevel() >= (lineWidth * 4)
end

local function awaitRefuel(lineWidth)
  repeat
    for i=1,16 do
      if turtle.getItemCount(i) > 0 then
        turtle.select(i)
        turtle.refuel()
      end
    end
  until fuelCheck(lineWidth)
end


local args = {...}
local width = #args > 0 and tonumber(args[1])
local startLeft = #args > 1 and #args[2] > 0 and string.lower(args[2]):sub(1,1) == 'l'

local turn, otherTurn = turtle.turnLeft, turtle.turnRight
if not startLeft then
    turn, otherTurn = otherTurn, turn
end

-- Width 1 means we're just digging a line
if width == 1 then
  turn = function() end
  otherTurn = function() end
end

if width < 1 then
  error("Width must be at least 1")
end

while true do
  if not fuelCheck(width) then
    print("I need more fuel")
    awaitRefuel()
  end
  forward()
  turn()
  line(width)
  otherTurn()
  
  turn, otherTurn = otherTurn, turn
end