local modemSide = "left"
local chestSlot = 15
local fuelSlot = 16
local minFuel = 500

rednet.open(modemSide)
print("Miner online")

local function refuel()
    if turtle.getFuelLevel() == "unlimited" then return end

    if turtle.getFuelLevel() < minFuel then
        turtle.select(fuelSlot)
        if turtle.getItemCount(fuelSlot) > 0 then
            turtle.refuel(1)
        else
            print("Out of fuel!")
        end
    end
end

local function inventoryFull()
    for i = 1, 14 do
        if turtle.getItemCount(i) == 0 then
            return false
        end
    end
    return true
end

local function unload()
    turtle.select(chestSlot)

    if turtle.placeDown() then
        for i = 1, 14 do
            turtle.select(i)
            turtle.dropDown()
        end

        turtle.select(chestSlot)
        turtle.digDown()
    else
        print("Could not place chest")
    end

    turtle.select(1)
end

local function mineStep()
    while turtle.detect() do
        turtle.dig()
        sleep(0.1)
    end

    refuel()

    if turtle.forward() then
        turtle.digUp()
        turtle.digDown()

        rednet.broadcast("move")
        sleep(0.3)
    else
        print("Could not move")
    end
end

while true do
    refuel()

    if inventoryFull() then
        unload()
    end

    mineStep()
end