Hello, I'm attempting to code a program that will make the mining turtle dig out an area defined by what is input. It will then go back to it's start location and then dig out tunnels every 3 blocks along. But for some reason it is acting weird, see the images below for an explanation:

Here is the route that it took (above ground just testing to show you the issue).
The blue is the second stage of the code where it should dig out the tunnels every 3 blocks along.



Here is the route it SHOULD of took!


Here is my code:

--Moving functions
function move(direction)
if direction == "forward" then
  if turtle.detect() then
   turtle.dig()
   turtle.forward()
  else
   turtle.forward()
  end
end
if direction == "left" then
  turtle.turnLeft()
  if turtle.detect() then
   turtle.dig()
   turtle.forward()
  else
   turtle.forward()
  end
end
if direction == "right" then
  turtle.turnRight()
  if turtle.detect() then
   turtle.dig()
   turtle.forward()
  else
   turtle.forward()
  end
end
end
-- Refuel the turtle
function refuelTurtle()
for i = 1, 16 do -- Loop through all the slots
  turtle.select(i) --Change the slot
  if turtle.refuel(0) then --is valid fuel
   turtle.refuel(turtle.getItemCount(i)) --Use half the stack of fuel
  else
   found = false
  end
end
return found
end
function digtunnels()
x = 0 --Turn every 3 blocks counter
y = 3 --Turn at end of max length counter

--Request the size of the tunnels
print("Enter how big you want the tunnels...")
size = read() - 1

--Calculate if there is enough fuel for the job
countRows = size / 3
frameSize = size * 4 - 4
neededFuel = math.floor(countRows + frameSize)
currentFuel = turtle.getFuelLevel()

if neededFuel < currentFuel then
  print("You have enough fuel, starting...")
else
  print("Needed amount of fuel: "..currentFuel..neededFuel)
  print("Press enter when you have added more fuel...")
  read()
  if refuelTurtle() == false then --Try and refuel
   print("Refueled, press enter to restart the program!")
   read()
   digtunnels()
  end
end

--Start the mining process
for k = 0, y do
  for b = 0, size do
   move("forward")
   turtle.digUp()
  end
  turtle.turnLeft()
end

--Made the outline, now dig the tunnels
--Turn left first, then switch between left and right
lr = 0
for k = 1, size do --Move along entire length
  if x == 4 then --Dig every 3 blocks
 
   --Turn left or right
   if lr == 0 then
    turtle.turnLeft()
    lr = 1
   elseif lr == 1 then
    turtle.turnRight()
    lr = 0
   end
  
   --Dig the length of the tunnel
   for m = 1, size do
    move("forward")
    turtle.digUp()
   end
  
   x = 0 --Reset counter
  end
 
  --Move forward
  move("forward")
  turtle.digUp()
  x = x + 1
end
end
digtunnels()