-- main method

-- reload API

os.unloadAPI('/utils/lib/tx')
os.loadAPI('/utils/lib/tx')

debug = tx.debug

function trace(msg)
    print(msg)
end

c_state = {}

function initialize()
    trace('called first_blood')
    -- setup the startup state
    tx.init{x=0, y=0, z=-1, o='north'}
    tx.select(1) 
    start_pos = tx.placemark('start')
    tx.state.move_mode = 'dig'
    tx.save_state()
    tx.info()
    
    c_state = {}
    c_state.first_tree_is_small = true
end

function first_blood()
    --[[
        Before anything really branches of into choices, do some predictable
        first few actions.
    ]]--
    tx.check_inventory() -- reset inv
    tx.dig() -- first oak wood
    tx.craft() -- first planks
    -- tx.assert_item_type(1, 'Oak planks')
    tx.refuel(4) -- first fuel, might as well use all 4
    debug('Fuel level = '..tx.getFuelLevel())
    tx.forward()
    tx.digUp{assume='Oak Wood'} -- oakwood
    temp_pos = tx.get_pos()
    -- tx.goto_placemark('start') exit()    
    tx.up()    
    while tx.detectUp() do
        tx.up()
        for i=1,4 do
            got_wood = tx.compare('Oak wood')
            if c_state.first_tree_is_small and tx.compare('Oak wood') then
                print('Discovery: the first oak tree is a big oak tree\n  (or adjacant to a big tree)')
                c_state.first_tree_is_small = false
            end
            if got_wood then
                assumption = 'Oak wood'
            else
                assumption = {'Oak sappling', 'Apple'}
            end
            tx.dig{assume=assumption}
            tx.left()
        end
    end
    tx.goto_pos(temp_pos)
    
    -- check down for more wood
    while tx.compareDown() do
        tx.down{assume='Oak Wood'}
    end
    
    -- keep track of position guaranteed to be able to grow a tree in (at some point)
    tx.placemark('tree_base')
    tx.save_state() 
    
    -- first one under here should be dirt or less likely sand...
    tx.digDown{assume={'Dirt', 'Sand'}}
    
    -- identify potential sappling from apple by trying to place it    
    -- mark pos
    -- 
    
    haz_cobble = false
    depth = 0
    while not haz_cobble do
        tx.down()
        depth = depth + 1
        for i=1,3 do
            tx.dig()
            tx.left()
        end
        tx.dig{assume={'Dirt', 'Sand', 'Cobble', 'Gravel', 'Iron ore'}}
        -- perform some voodoo to guess if we have enough (10+) cobble
        -- stub
        haz_cobble = depth >= 40
    end
    
    tx.goto_placemark('start')
end

initialize()
first_blood()
