-- Copyright (c) Odd Strabo <oddstr13 at openshell.no>
-- License: MIT - http://opensource.org/licenses/MIT


local function go(dir, n)
  if n == nil then n = 1 end
  for i=1,n do
    while not dir() do
      local fl = turtle.getFuelLevel()
      if fl ~= "unlimited" and fl == 0 then
        turtle.select(1)
        turtle.refuel()
      end
    end
  end
end

local function forward(n)
  go(turtle.forward, n)
end

local function isHome()
  return peripheral.getType("bottom") == 'me_interface'
end

local function refillFuel()
  turtle.select(1)
  local c = turtle.getItemSpace(1)
  while c >= 8 do
    if not turtle.suckUp() then
      break
    end
    c = turtle.getItemSpace(1)
    sleep(0.1)
  end
end

local function refillSaplings()
  turtle.select(2)
  while turtle.suckDown() do
    sleep(0.1)
  end
end

local function refill()
  refillFuel()
  refillSaplings()
end

local function plant()
  for i=2,16 do
    if turtle.getItemCount(i) > 0 then
      turtle.select(i)
      break
    end
  end
  turtle.placeDown()
end



local tr = false
local function turn()
  if tr then
    turtle.turnRight()
  else
    turtle.turnLeft()
  end
end

local function turnGo()
  turn()
  forward()
  turn()
  tr = not tr
end

local w = 14 -- Even number.
local h = 19

local function main()
  tr = true
  
  refill()

  forward()
  for i=1,w do
    for j=1,h-1 do
      plant()
      forward()
    end
    if i ~= w then
      plant()
      turnGo()
    end
  end
  plant()
  forward()
  tr = not tr
  turn()
  for i=1,w-1 do
    forward()
  end
  turn()
end

while true do
  if isHome() then
    main()
  else
    print("I'm lost :'(")
  end
  sleep(120)
end
