--[[

How to keep track of a task, while being reboot save.
-- continuously save state [task state + turtle state]
-- on startup restore state
-- resume task

]]--



local args = { ... }
if #args < 1 or #args > 3 then
	print( "Usage: excavate <size_x> [size_z] [levels]" )
	return
end

size_x = tonumber( args[1] )
if size_x < 1 then
	print( "Excavate size_x must be positive" )
	return
end

size_z = tonumber( args[2] ) or size_x
if size_z < 1 then
	print( "Excavate size_z must be positive" )
	return
end

levels = tonumber( args[3] ) or 999
if levels < 1 then
	print( "Excavate levels must be positive" )
	return
end

if not tx then
    error('excavate 2 requires tx')
end

print(size_x)
print(size_z)
	
local cur_depth = 0
local unloaded = 0
local collected = 0

local xPos,zPos = 0,0
local xDir,zDir = 0,1

local goTo -- Filled in further down
local refuel -- Filled in further down

local home_x = tx.state.x
local home_y = tx.state.y
local home_z = tx.state.z
local home_o = tx.state.o

use_slots = 12

task_state = {}


function forward()
    turtle.digUp()
    turtle.digDown()
    if not space_left() then
        unload()
    end
    tx.fw()
end

function turn(to_right)
    turtle.digUp()
    turtle.digDown()
    if to_right == 1 then
        fturn = tx.right
    else
        fturn = tx.left
    end
    fturn()
    forward()
    fturn()
end

function space_left()
    -- +margin	
	local full = true
	for i=use_slots,1,-1 do
		if turtle.getItemCount(i) == 0 then
		    return true
		end
	end
end

function unload()
    cur_x = tx.state.x
    cur_y = tx.state.y
    cur_z = tx.state.z
    cur_o = tx.state.o
    tx.goto(tx.state.x, home_y, tx.state.z)
    local o = home_o + 2
    o = (o - 1) % 4
    o = o + 1
    tx.goto(home_x, home_y, home_z, o)

	for i=1,use_slots do
	    turtle.select(i)
		turtle.drop()
	end
	turtle.select(1)
	
    tx.goto(cur_x, home_y, cur_z)
    tx.goto(cur_x, cur_y, cur_z, cur_o)
	
end

function level()
    for z=1,size_z do
        for x=1,size_x do
            forward()
        end
        if z ~= size_z then
            turn(z % 2)
        end
    end
end

tx.state.move_mode = 'dig'
level()
tx.goto(home_x, home_y, home_z, home_o)
