

local dug = false
local length = 0
local tArgs = { ... }
local orientation = 1
local offset = { 0, 0, 0 }


function rotate(dir)
    --  rotate
    if dir == 'left' then 
        turtle.turnLeft()
        orientation = orientation - 1
    elseif dir == 'right' then
        turtle.turnRight()
        orientation = orientation + 1 
    end

    -- fix orientation if invalid
    if(orientation < 1) then orientation = orientation + 4 end
    if(orientation > 4) then orientation = orientation - 4 end
end

function advanceOffset()
    if orientation == 1 then        offset[1] = offset[1] + 1
    elseif orientation == 2 then    offset[2] = offset[2] + 1
    elseif orientation == 3 then    offset[1] = offset[1] - 1
    elseif orientation == 4 then    offset[2] = offset[2] - 1
    end
end

function move()
    local attempt = 0;
    while not turtle.forward() do
        print("attempting move at offset:",offset[1],offset[2],offset[3])
        -- print(offset)
        attempt = attempt + 1
    end
    advanceOffset()
end

function usage()
    return "dig <length>"
end

function checkInv()
    local emptySpace = false
    for i=1,16 do
        if turtle.getItemDetail(i) == nil then 
        print("found empty space")
            emptySpace = true 
            break 
        end
    end
    return emptySpace
end

local waypoint = { 0, 0, 0}
function setWaypoint()
    waypoint = offset
end

function offsetEq(o1, o2)
    if o1[1] == o2[1] and o1[2] == o2[2] and o1[3] == o2[3] then
        return true
    else
        return false
    end
end

function returnHome()
    while not (orientation == 3) do 
        rotate("left")
    end
    while not offsetEq(offset, {0,0,0}) do
        print("offset is not {0,0,0}","proof:",offset[1],offset[2],offset[3])
        move()
    end
end

function emptyInv()
    for i=1,16 do
        turtle.select(i)
        turtle.drop()
    end
end

function returnToWaypoint()
    while not (orientation == 1) do 
        rotate("right")
    end
    while not offsetEq(offset, waypoint) do
        move()
    end
end

function dig()
    -- dig out next position
    turtle.dig()
    move()
    turtle.digUp()
    turtle.digDown()
end

function doDig()
    for i=1,length do
        -- check if we still have free inventory space
        spaceleft = checkInv()

        if spaceleft then
            dig()
        else 
            setWaypoint()
            returnHome()
            emptyInv()
            returnToWaypoint()
            dig()
        end
        print(i)
    end
    returnHome()
    emptyInv()
end

if tArgs[1] and type(tonumber(tArgs[1])) == "number" then
    length = tonumber(tArgs[1]);
    doDig()
else
    print(usage())
end
