View difference between Paste ID: ayN8q31J and xXLEFRiK
SHOW: | | - or go back to the newest paste.
1
--[[
2
Name: storeKeeperV
3
Version: 1.4
4
Description: Put items away in an inventory system made up of a network of stacked chests.  Be able
5
to store, identify and count the contents of each chest and be able to retrieve items when requested
6
by the InventoryControl program.
7
8
Note:  This program has been extensively rewritten from the original program written by nitrogetfingers used in his Turtle Butler example.
9
The use of the parallel option was removed because of problems using it on a server.
10
11
Date: 01/14/13
12
Author: Severino
13
14
Future enhancements planned:
15
- Unloading mine carts
16
17
]]--
18
19
-- Current inventory location
20
location = 0
21
locLevel = 0
22
locDir = 0
23
-- Current Inventory Location
24
currentLocation = locLevel..","..locDir
25
-- Current orientation within the room (1 = forward, 2=right, 3=back, 4=left)
26
orientation = 1
27
-- Flag to abort mission.
28
abortMission = false
29
-- Maximum slot to use to transfer inventory
30
maxSlot = 15
31
-- Slot to use to store fuel.
32
fuelSlot = 16
33
-- Setup Directions.
34
invDir = 1
35
fuelDir = 2
36
unknownDir = 4
37
-- Inventory Names
38
inventoryName = {}
39
-- Home Terminal
40
orderComputer = nil
41
storeKeeperID = nil
42-
modemLocation = nil
42+
43
-- Has Pick Axe
44-
print("Looking for modem,")
44+
45-
if peripheral.isPresent("left") and peripheral.getType("left")=="modem" then
45+
46-
  modemLocation = "left"
46+
47-
elseif peripheral.isPresent("right") and peripheral.getType("right")=="modem" then
47+
48-
  modemLocation = "right"
48+
49-
elseif peripheral.isPresent("top") and peripheral.getType("top")=="modem" then
49+
50-
  modemLocation = "top"
50+
51-
elseif peripheral.isPresent("back") and peripheral.getType("back")=="modem" then
51+
52-
  modemLocation = "back"
52+
53-
elseif peripheral.isPresent("bottom") and peripheral.getType("bottom")=="modem" then
53+
54-
  modemLocation = "bottom"
54+
55-
else
55+
56-
  print("No modem")
56+
57-
  return
57+
58
    if fs.exists(tableName) then
59-
print("Modem found on "..modemLocation)
59+
60
      vars = file.readAll()
61
      file.close()
62
      tableData = textutils.unserialize(vars)
63
    else
64
      file = fs.open(tableName, "w")
65
      tableData = {}
66
      vars = textutils.serialize(tableData)
67
      file.write(vars)
68
      file.close()
69
    end
70
    return tableData
71
end
72
function reportInventory(computerId)
73
  invData = textutils.serialize(inventoryName)
74
  if computerId == nil then
75
    rednet.broadcast("inventory"..invData)
76
  else
77
    rednet.send(computerId, "inventory"..invData)
78
  end
79
end
80
function identifyInventory()
81
  -- If there is inventory left and there are empty chests, put it in the empty chests
82
  if not isTurtleEmpty() then 
83
    if not goToStart() then return end
84
    emptyInventory()
85
  end
86
  
87
  -- This function locates inventory locations that have not been identified and requests descriptions.
88
  local level = 1
89
  local dir = 0
90
  local slot = 0
91
  local locationsLevel = {}
92
  local locationsDir = {}
93
  local locationsName = {}
94
  local locationNotEmpty = true
95
  setStatus("Retrieving Inventory")
96
  while slot < maxSlot and locationNotEmpty do
97
    for dir = 1,4 do
98
      local invLoc = level..","..dir
99
      local name, qty = getInventoryNameQty(invLoc)
100
      if name == "_" then
101
        gotoLocation(level,dir)
102
        if turtle.detect() then
103
          slot = slot + 1
104
          turtle.select(slot)
105
          if turtle.suck() then
106
            turtle.drop(turtle.getItemCount(slot)-1)
107
            locationsLevel[slot] = level
108
            locationsDir[slot] = dir
109
            print("at "..invLoc)
110
            setStatus("at "..invLoc)
111
            if qty ~= nil then
112
              if tonumber(qty) > 0 then
113
                qty = qty - 1
114
                inventoryName[invLoc] = "_#"..qty
115
              end
116
            end
117
          else
118
            slot = slot - 1
119
          end
120
        else
121
          locationNotEmpty = false
122
          break
123
        end
124
      end
125
      if slot == maxSlot then break end
126
    end
127
    level = level + 1
128
  end
129
  if goToStart() then
130
    if not isTurtleEmpty() then
131
      -- Something was loaded.  Get names for each item in
132
      local i = 1
133
      while locationsLevel[i] ~= nil do
134
        if turtle.getItemCount(i) > 0 then
135
          level = locationsLevel[i]
136
          dir = locationsDir[i]
137
          local name, qty = getInventoryNameQty(invLoc)
138
          name = nil
139
          while name == nil do
140
            setStatus("Identify slot "..i)
141
            term.write("Identify slot "..i.." (b=back):")
142
            name = io.read()
143
          end
144
          if string.lower(name) == "b" then
145
            if i > 1 then i = i - 2 else i = i - 1 end
146
          else
147
            inventoryName[level..","..dir] = name.."#"..qty
148
            setStatus("identify"..level..","..dir.."-"..name)
149
          end
150
        end
151
        i = i + 1
152
      end
153
      saveTable(inventoryName, "inventory")
154
      -- Now go and put everything away.
155
      setStatus("Putting inventory back.")
156
      local i = 1
157
      while locationsLevel[i] ~= nil do
158
        if turtle.getItemCount(i) > 0 then
159
          level = locationsLevel[i]
160
          dir = locationsDir[i]
161
          returnItemToInventory(i, level, dir)          
162
        end
163
        i = i + 1
164
      end
165
      goToStart()
166
    else
167
      setStatus("done identifying.")
168
    end
169
  end
170
end
171
-- Is there anything in the turtle.
172
function isTurtleEmpty()
173
  for s=1,maxSlot,1 do
174
    if turtle.getItemCount(s) > 0 then return false end
175
  end
176
  return true
177
end
178
-- Change the orientation of the turtle
179
function changeOrientation(dir)
180
  if dir < 1 then dir = dir + 4 end
181
  if dir > 4 then dir = dir - 4 end
182
  while orientation ~= dir do
183
    if (orientation - dir) == -3 or (orientation - dir) == 1 then
184
      turtle.turnLeft()
185
      orientation = orientation - 1
186
    else
187
      turtle.turnRight()
188
      orientation = orientation + 1
189
    end
190
        if orientation > 4 then
191
      orientation = 1
192
    elseif orientation == 0 then
193
      orientation = 4
194
    end
195
    end
196
end
197
--Go to starting position
198
function goToStart()
199
  print("Going to start.")
200
  setStatus("going to start")
201
  -- Move out of chest shaft.
202
  local ceilingFound = false
203
  for a=1,70 do
204
     
205
    if not turtle.detectUp() then turtle.up() else
206
      ceilingFound = true
207
      break
208
    end
209
  end
210
  if not ceilingFound then
211
    for b=1,70 do
212
       
213
      turtle.down()
214
    end
215
    print("Ceiling not found.")
216
    return false
217
  end
218
  changeOrientation(invDir)  -- Now facing material chest
219-
  refuel()
219+
220
  -- Reset location to indicate at Start position.
221
  location = 0
222
  locLevel = 0
223-
    refuel()
223+
224
  currentLocation = locLevel..","..locDir
225
  changeOrientation(invDir)
226
  return true
227
end
228
-- Go to a specific inventory location.
229
function gotoLocation(level, dir)
230
  if locDir == 0 then
231-
      refuel()
231+
232
    if not turtle.down() then return false end  -- Now even with floor
233
    if not turtle.down() then return false end  -- Now 1 below fllor
234
    if not turtle.down() then return false end  -- Now even with the first level of chest.
235
    locLevel = 1
236
    changeOrientation(1)
237
    locDir = 1
238
    currentLocation = locLevel..","..locDir
239
  end
240
  while level ~= locLevel do
241
     
242
    if locLevel < level  then
243
      if turtle.down() then locLevel = locLevel + 1 else return false end
244
    else
245
      if turtle.up() then locLevel = locLevel - 1 else return false end
246
    end
247-
function refuel()
247+
248-
  -- Refuel
248+
249-
  if turtle.getFuelLevel() < 100 then
249+
250-
    print("Refueling.")
250+
251-
    setStatus("refueling")
251+
252-
    turtle.select(fuelSlot)
252+
253-
        changeOrientation(fuelDir)
253+
254-
    while turtle.getFuelLevel() < 100 do
254+
255-
      if turtle.getItemCount(fuelSlot) <= 1 then
255+
256-
        if not turtle.suck() then
256+
257-
          print("Place more fuel in slot "..fuelSlot)
257+
258-
          setStatus("waiting for fuel")
258+
259-
          sleep(20)
259+
260
    turtle.down()  -- Now 1 below fllor
261
    turtle.down()  -- Now even with the first level of chest.
262-
      turtle.refuel(1)
262+
263
    changeOrientation(1)
264-
    -- Put the extra fuel back.
264+
265-
    print("Refuelled to level "..turtle.getFuelLevel())
265+
266
  elseif locDir == 4 then
267
    if turtle.detectDown() then
268-
    changeOrientation(invDir)
268+
269
      return false
270
    else
271
      -- Move down to the next chest.
272
      while not turtle.down() do
273
        setStatus("blocked at level "..locLevel)
274
        sleep(10)
275
      end
276
      locLevel = locLevel + 1
277
      locDir = 1
278
      changeOrientation(locDir)
279
      currentLocation = locLevel..","..locDir
280
      -- Check to see if there isn't a chest there.
281
      if not turtle.detect() then return false end
282
    end
283
  else
284-
    refuel()
284+
285
    changeOrientation(locDir)
286
    currentLocation = locLevel..","..locDir
287
    -- Check to see if there isn't a chest there.
288
    if not turtle.detect() then return false end
289
  end
290
  return true
291
end
292
293
-- Load Inventory To Put Away
294
function loadInventory()
295
    -- Pick up all of the items in the chest in front of the turtle.
296
    -- Set the flag that the inventory is empty.
297
    inventoryLoaded = false
298
    -- Start filling at slot 2.  Keep slot 1 clear for comparing to contents of chest.
299
	s=2
300
	while s <= maxSlot do    
301
		turtle.select(s)
302
		if turtle.suck() then
303
			-- Something was picked up so reset the flag.
304
			inventoryLoaded = true
305
		else
306
			-- The inventory chest is empty.
307
			break
308
		end
309
		-- Move to the next slot in the turtle.
310
		s = s + 1
311
	end
312
	return inventoryLoaded
313
end
314
315
-- Empty non-identified items
316
function emptyInventory()
317
	print("Emptying inv.")
318
  setStatus("emptying inventory")
319
	changeOrientation(unknownDir)
320
	-- Dump everything into chest of unknown material.
321
	for s=1,maxSlot,1 do
322
		turtle.select(s)
323
		turtle.drop()
324
	end
325
	-- Return to Start position
326
	changeOrientation(invDir)
327
end
328
function digFoward()
329
  turtle.select(6)
330
  while turtle.detect() do
331
    turtle.dig()
332
    sleep(.5)
333
  end
334
end
335
function selectFill()
336
  for s=7,15 do
337
    turtle.select(s)
338
    if turtle.compareTo(6) then return end
339
  end
340
  turtle.select(6)
341
end
342
function placeSeal()
343
  selectFill()
344
  while not turtle.detect() do
345
    turtle.place()
346
    sleep(.5)
347
  end
348
end
349
function placeSealDown()
350
  selectFill()
351
  while not turtle.detectDown() do
352
    turtle.placeDown()
353
    sleep(.5)
354
  end
355
end
356
function digDown()
357
  turtle.select(6)
358
  while turtle.detectDown() do
359
    turtle.digDown()
360
    sleep(.5)
361
  end
362
end
363
function goForward()
364
  while not turtle.forward() do
365
    print("Forward blocked")
366
    sleep(4)
367
  end
368
end
369
function goBack()
370
  while not turtle.back() do
371
    print("Back blocked")
372
    sleep(4)
373
  end
374
end
375
function selectChest()
376
  for s=5,15 do
377
    turtle.select(s)
378
    if turtle.compareTo(1) then return true end
379
  end
380
  if turtle.getItemCount(1) > 0 then
381
    turtle.select(1)
382
    return true 
383
  end
384
  return false
385
end
386
function placeChest()
387
  selectChest()
388
  turtle.place()
389
end
390
function placeChestUp()
391
  selectChest()
392
  turtle.placeUp()
393
end  
394
function selectGlass()
395
  for s=5,15 do
396
    turtle.select(s)
397
    if turtle.compareTo(2) then return true end
398
  end
399
  turtle.select(2)
400
  if turtle.getItemCount(2) > 0 then
401
    turtle.select(2)
402
    return true 
403
  end
404
  return false
405
end
406
function placeGlass()
407
  if selectGlass() then
408
    turtle.place()
409
  else
410
    placeSeal()
411
  end
412
end
413
function selectTorch()
414
  for s=5,15 do
415
    turtle.select(s)
416
    if turtle.compareTo(3) then return true end
417
  end
418
  if turtle.getItemCount(3) > 0 then
419
    turtle.select(3)
420
    return true 
421
  end
422
  return false
423
end
424
function placeTorchUp()
425
  if selectTorch() then 
426
    turtle.placeUp()
427
    return true
428
  end
429
  return false
430
end
431
function selectLadder()
432
  for s=5,15 do
433
    turtle.select(s)
434
    if turtle.compareTo(4) then return true end
435
  end
436
  if turtle.getItemCount(4) > 0 then
437
    turtle.select(4)
438
    return true 
439
  end
440
  return false
441
end
442
function placeLadderUp()
443
  if selectLadder() then
444
    turtle.placeUp()
445
    return true
446
  end
447
  return false
448
end
449
function placeSign(message)
450
  if hasSigns then
451
    if not turtle.detect() then
452
      goForward()
453
      if not turtle.detect() then placeSeal() end
454
      goBack()
455
    end
456
    turtle.select(5)
457
    turtle.place(message)
458
  end
459
end
460
-- Create Initial Chest Setup
461
function Initialize()
462
  if not hasPickAxe then
463
    print("Turtle must have a pick axe to")
464
    print("be able to create warehouse shaft.")
465
    return false
466
  end
467
  -- First check that you are facing a wall.
468
  local wallDetected = false
469
  for a=1,4 do
470
    if turtle.detect() then 
471
      wallDetected = true
472
      break
473
    end
474
    turtle.turnRight()
475
  end
476
  if not wallDetected then
477
    print("Turtle must be next to a wall to create initial setup.")
478
    return false
479
  end
480
  -- Now give instructions about where to put chests.
481
  while turtle.getItemCount(fuelSlot) < 5 do
482
    print("Place 5+ fuel in slot "..fuelSlot..".")
483
    term.write("Ready? (Y/N):")
484
    continue = string.upper(io.read())
485
    if continue ~= "Y" then return false end
486
  end
487
  while turtle.getItemCount(1) < 10 do
488
    print("Place the following material in the slots.")
489
    print("Slot 1: 30+ chests")
490
    print("Slot 2: 30+ glass blocks")
491
    print("Slot 3: 20+ torches")
492
    print("Slot 4: 30+ ladders")
493
    print("Slot 5: 3 signs")
494
    print("Slot 6: Material to seal walls")
495
    print("Place additional chests, glass and material in other slots.")
496
    term.write("Ready? (Y/N):")
497
    continue = string.upper(io.read())
498
    if continue ~= "Y" then return false end
499
  end
500
  -- Check for clearance to place chests
501
   
502
  rightOk = false
503
  backOk = false
504
  leftOk = false
505
  upOk = false
506
  hasGlass = turtle.getItemCount(2) > 0
507
  hasTorches = turtle.getItemCount(3) > 0
508
  hasLadders = turtle.getItemCount(4) > 0
509
  hasSigns = turtle.getItemCount(5) > 0
510
  while not (rightOk and leftOk and backOk and upOk) do
511
    -- Check to the right
512
    turtle.turnRight()
513
    -- Facing right
514
    if not turtle.detect() then
515
      if turtle.forward() then
516
        if not turtle.detect() then rightOk = true end
517
        turtle.back()
518
      end
519
    end
520
    -- Check to the back.
521
    turtle.turnRight()
522
    -- Facing front
523
    if not turtle.detect() then backOk = true end
524
    -- Check to the left
525
    turtle.turnRight()
526
    -- Facing left
527
    if not turtle.detect() then
528
      if turtle.forward() then
529
        if not turtle.detect() then leftOk = true end
530
        turtle.back()
531
      end
532
    end
533
    -- Check Up
534
    if not turtle.detectUp() then upOk = true end
535
    turtle.turnRight()
536
    -- Facing back
537
    if not upOk then print("Space above turtle must be clear.") end
538
    if not rightOk then print("2 spaces to right must be clear.") end
539
    if not backOk then print("Space behind turtle must be clear.") end
540
    if not leftOk then print("2 spaces to left must be clear.") end
541
    if not (rightOk and leftOk and backOk and upOk) then
542
      print("Continue?")
543
      cont = io.read()
544-
  refuel()
544+
545
  end
546
  ---------- BLOCK PATTERN ---------
547
  --             Back
548
  --               X
549
  --            P  U  W 
550
  --         R  O  T  V  Y
551
  -- Left 11 N  M  S  A  B 12 Right
552
  --      10 L  I  G  E  C 13
553
  --       9 K  J  H  F  D 14
554
  --         8  1  2  3  4
555
  --            7  6  5
556
  --             Front
557
  -- Everthing ready, start setting things up.
558
   
559
  -- Place double unidentified chest
560
  turtle.turnRight()
561
  -- Facing right
562
  goForward()
563
  placeChest()
564
  goBack()
565
  placeChest()
566
  -- Now put a sign on it.
567
  if hasSigns then
568
    if turtle.up() then
569
      turtle.turnRight()
570
      if turtle.forward() then
571
        turtle.turnLeft()
572
        if turtle.forward() then
573
          if turtle.forward() then
574
            turtle.turnLeft()
575
            placeSign("\nOverflow\nInventory")
576
            turtle.turnRight()
577
            turtle.back()
578
          end
579
          turtle.back()
580
        end
581
        turtle.turnRight()
582
        turtle.back()
583
      end
584
      turtle.turnLeft()
585
      turtle.down()
586
    end
587
  end
588
  -- Place double fuel chest
589
  turtle.turnRight()
590
  turtle.turnRight()
591
  -- Facing left
592
  goForward()
593
  placeChest()
594
  goBack()
595
  placeChest()
596
  -- Now put some fuel in it.
597
  turtle.select(fuelSlot)
598
  turtle.drop(1)
599
  -- Now put a sign on it.
600
  if hasSigns then
601-
  refuel()
601+
602
      turtle.turnLeft()
603
      if turtle.forward() then
604
        turtle.turnRight()
605
        if turtle.forward() then
606
          if turtle.forward() then
607
            turtle.turnRight()
608
            placeSign("\nStoreKeeper\nFuel")
609
            turtle.turnLeft()
610
            turtle.back()
611
          end
612
          turtle.back()
613
        end
614
        turtle.turnLeft()
615
        turtle.back()
616
      end
617
      turtle.turnRight()
618
      turtle.down()
619
    end
620
  end
621
  -- Place retrieval chest
622
  turtle.turnRight()
623
  -- Facing back
624
  placeChestUp()
625
  -- Now put a sign on it.
626
  if turtle.back() then
627
    if turtle.up() then
628
      if turtle.up() then
629
        placeSign("\nRequested\nItems")
630
        turtle.down()
631
      end
632
      turtle.down()
633
      turtle.forward()
634
    end
635
  end
636
  -- Place unknown item chest
637
  turtle.turnRight()
638
  turtle.turnRight()
639
  -- Facing front
640
  goForward()
641
  placeChest()
642
  goBack()
643
  placeChest()
644
  turtle.turnRight()
645
  turtle.turnRight()
646
  -- Facing back
647
648
  -- Now replace the floor with glass blocks and a crawl hole  
649
   
650
  local level = 0
651
  turtle.turnRight()
652
  -- Facing right
653
  turtle.digDown()
654
  turtle.down()
655
  level = level + 1
656
  -- If we have glass blocks then replace floor with glass blocks
657
  -- Replace floor to right
658
  digFoward()
659
  goForward() -- A
660
  turtle.turnLeft() -- Facing back
661
  placeGlass() -- V
662
  turtle.turnRight() -- Facing left
663
  digFoward()
664
  goForward() -- B
665
  turtle.turnLeft() -- Facing back
666
  placeGlass() -- Y
667
  turtle.turnRight() -- Facing left
668
  digFoward()
669
  goForward() -- 12
670
  turtle.turnRight() -- Facing front
671
  digFoward()
672
  goForward() -- 13
673
  digFoward()
674
  goForward() -- 14
675
  digFoward()
676
  placeSeal() -- 15
677
  goBack() -- 13
678
  placeSeal() -- 14
679
  goBack() -- 12
680
  placeSeal() -- 13
681
  turtle.turnLeft() -- Facing right
682
  goBack() -- B
683
  placeSeal() -- 12
684
  turtle.turnRight() -- Facing front
685
  digFoward()
686
  goForward() -- C
687
  digForward()
688
  goForward() -- D
689
  goBack() -- C
690
  goBack() -- B
691
  placeGlass() -- C
692-
  refuel()
692+
693
  goBack() -- A
694
  placeGlass() -- B
695
  turtle.turnRight() -- Facing front
696
  digFoward()
697
  placeGlass() -- E
698
  turtle.turnLeft() -- Facing right
699
  goBack() -- Start
700
  placeGlass() -- A
701
  turtle.turnRight() -- Facing front
702
  -- Replace floor to front with glass
703
  digFoward()
704
  goForward() -- G
705
  digFoward()
706
  goForward() -- H
707
  digFoward()
708
  goForward() -- 2
709
  turtle.turnLeft() -- Facing right
710
  digFoward()
711
  goForward() -- 3
712
  placeGlass() -- 4
713
  goBack() -- 2
714
  placeGlass() -- 3
715
  turtle.turnRight() -- Facing front
716
  turtle.turnRight() -- Facing left
717
  digFoward()
718
  goForward() -- 1
719
  digForward()
720
  goForward() -- 8
721
  placeGlass() -- 16
722
  goBack() -- 1
723
  placeGlass() -- 8
724
  goBack() -- 2
725
  placeGlass() -- 1
726
  turtle.turnLeft() -- Facing front
727
  goBack() -- H
728
  placeGlass() -- 2
729
  turtle.turnLeft() -- Facing right
730
  digFoward()
731
  goForward() -- F
732
  digFoward()
733
  goBack() -- H
734
  placeGlass() -- F
735
  turtle.turnRight() -- Facing front
736
  turtle.turnRight() -- Facing left
737
  digFoward()
738
  goForward() -- J
739
  digFoward() -- K
740
  goForward() -- K
741
  placeGlass() -- 9
742
  goBack() -- J
743
  goBack() -- H
744
  placeGlass() -- J
745
  turtle.turnLeft() -- Facing front
746
  goBack() -- G
747
  placeGlass() -- H
748
  goBack() -- S
749
  placeGlass() -- G
750
  -- Replace floor on left
751
  turtle.turnRight() -- Facing left
752
  digFoward()
753
  goForward() -- M
754
  turtle.turnLeft() -- Facing front
755
  digFoward()
756
  placeGlass() -- I
757
  turtle.turnRight() -- Facing left
758
  digFoward()
759
  goForward() -- N
760
  digForward()
761
  goForward() -- 11
762
  turtle.turnLeft() -- Facing front
763
  placeGlass() -- 10
764
  turtle.turnRight() -- Facing left
765
  goBack() -- N
766
  turtle.turnLeft() -- Facing front
767
  digFoward()
768
  placeGlass() -- L
769
  turtle.turnRight() -- Facing left
770
  placeSeal() -- 11
771
  goBack() -- M
772
  placeGlass() -- N
773
  goBack() -- Start
774
  placeGlass() -- M
775
  turtle.turnRight() -- Facing back
776
  -- Put fill in for the back
777
  digForward()
778
  goForward() -- T
779
  turtle.turnLeft() -- Facing left
780
  digForward() -- O
781
  goForward() -- O
782
  placeGlass() -- R
783
  goBack() -- T
784
  placeGlass() -- O
785
  turtle.turnRight() -- Facing back
786
  digForward() -- U
787
  goForward() -- U
788
  turtle.turnLeft() -- Facing left
789
  placeSeal() -- P
790
  turtle.turnRight() -- Facing back
791
  placeGlass() -- X
792
  turtle.turnRight() -- Facing right
793
  placeGlass() -- W
794
  turtle.turnLeft() -- Facing back
795
  goBack() -- T
796
  placeGlass() -- U
797
  goBack() -- S
798
  placeGlass() -- T w
799
  turtle.turnRight() -- Facing right
800
  turtle.digDown()
801
  turtle.down()
802
  level = level + 1
803
  -- Now start placing chests for warehouse until we run out of chests.
804
  -- Clear out space above chests.
805
   
806
  for d=1,4 do
807
    digFoward()
808
    goForward() -- 1=A, 2=G, 3=M, 4=T
809
    if d == 1 or d == 4 then
810
      turtle.turnLeft() -- Facing 1=back, 3=left
811
      placeSeal() -- 1=V, 4=O
812
      turtle.turnRight() -- Facing 1=right, 3=back
813
    elseif d == 2 or d == 4 then
814
      turtle.turnLeft() -- Facing right
815
      if d == 2 then digFoward() else placeSeal() end -- O
816
      turtle.turnRight() -- Facing front
817
      turtle.turnRight() -- Facing left
818
      if d == 2 then digFoward() else placeSeal() end -- V
819
      turtle.turnLeft() -- Facing front
820
    end
821
    digFoward()
822
    goForward() -- 1=B, 2=H, 3=N, 4=U
823
    if d == 1 or d == 4 then
824
      placeSeal() -- 1=12, 4=X
825
      turtle.turnLeft() -- Facing 1=back, 4=left
826
      placeSeal() -- 1=Y, 4=P
827
      turtle.turnRight() -- Facing 1=right, 4=back
828
      turtle.turnRight() -- Facing 1=front, 4=right
829
      if d == 1 then
830
        digFoward()
831
        placeGlass() -- C
832
      elseif d == 4 then placeSeal() end -- W
833
      turtle.turnLeft() -- Facing 1=right, 4=back
834
    elseif d == 2 then
835
      turtle.turnLeft() -- Facing 2=right
836
      digForward() -- F
837
      goForward() -- F
838
      digForward() -- D
839
      goForward() -- D
840
      placeSeal() -- 14
841
      goBack() -- F
842
      goBack() -- H
843
      placeGlass() -- F
844
      turtle.turnRight() -- Facing front
845
      turtle.turnRight() -- Facing left
846
      digForward()
847
      goForward() -- J
848-
  refuel()
848+
849
      goForward() -- K
850
      placeSeal() -- 9
851
      turtle.turnLeft() -- Facing front
852
      placeSeal() -- 8
853
      turtle.turnRight() -- Facing left
854
      goBack() -- J
855
      goBack() -- H
856
      placeGlass() -- J
857
      turtle.turnLeft() -- Facing front
858
      digForward()
859
      goForward() -- 2
860
      placeSeal() -- 6
861
      turtle.turnLeft() -- Facing right
862
      digForward() -- 3
863
      goForward() -- 3
864
      placeSeal() -- 4
865
      goBack() -- 2
866
      placeGlass() -- 3
867
      turtle.turnRight() -- Facing front
868
      turtle.turnRight() -- Facing left
869
      digForward() -- 1
870
      placeGlass() -- 1
871
      turtle.turnLeft() -- Facing front
872
      goBack() -- H
873
    elseif d == 3 then
874
      placeSeal() -- 11
875
      turtle.turnLeft() -- Facing front
876
      digForward()
877
      placeGlass() -- L
878
      turtle.turnRight() -- Facing left
879
      turtle.turnRight() -- Facing back
880
      placeSeal() -- R
881
      turtle.turnLeft() -- Facing left      
882
    end
883
    goBack() -- 1=A, 2=G, 3=M, 4=T
884
    goBack() -- Start
885
    turtle.turnRight() -- Facing 1=front, 2=left, 3=back, 4=right
886
  end
887
  -- Facing right
888
  -- S
889
  -- Now start adding layers of chests until they are all gone.
890
  while turtle.getItemCount(1) > 1 do
891
     
892
    turtle.digDown()
893
    turtle.down()
894
    level = level + 1
895
    for d=1,4 do
896
      -- Facing 1=right, 2=front, 3=left, 4=back
897
      turtle.select(5)
898
      digForward() -- 1=A, 2=G, 3=M, 4=T
899
      goForward() -- 1=A, 2=G, 3=M, 4=T      
900
      if d == 1 or d == 4 then
901
        turtle.turnLeft() -- Facing 1=back, 3=left
902
        placeSeal() -- 1=V, 4=O
903
        turtle.turnRight() -- Facing 1=right, 3=back
904
      elseif d == 2 or d == 4 then
905
        turtle.turnLeft() -- Facing right
906
        if d == 2 then
907
          digFoward()
908
          if (level-2)%6 == 0 then placeGlass() else -- E
909
            goForward()
910
            goBack()
911
          end
912
        else placeSeal() end -- O
913
        turtle.turnRight() -- Facing front
914
        turtle.turnRight() -- Facing left
915
        if d == 2 then
916
          digFoward()
917
          if (level-2)%6 == 0 then placeGlass() else -- I
918
            goForward()
919
            goBack()
920
          end 
921
        else placeSeal() end -- V
922
        turtle.turnLeft() -- Facing front
923
      end
924
      digForward() -- 1=B, 2=H, 3=N, 4=U
925
      goForward() -- 1=B, 2=H, 3=N, 4=U
926
      if (d == 1) then
927
        placeSeal() -- 12
928
        turtle.turnLeft() -- Facing back
929
        placeSeal() -- Y
930
        turtle.turnRight() -- Facing right
931
        turtle.turnRight() -- Facing front
932
        digForward() -- C
933
        goForward()
934-
    refuel()
934+
935
        if not(level%6 == 0 or (level-1)%6 == 0) then
936
          placeGlass() -- F
937
        else
938
          goForward() -- C
939
          turtle.turnLeft() -- Facing right
940
          placeSeal() -- 13
941
          turtle.turnRight() -- Facing front
942
          goBack() -- B
943
        end
944
        turtle.turnLeft() -- Facing 2=right        
945
      elseif (d == 2) then
946
        turtle.turnLeft() -- Facing 2=right
947
        digForward() -- F
948
        goForward() -- F
949
        digForward() -- D
950
        goForward() -- D
951
        placeSeal() -- 14
952
        placeLadderUp() -- D
953
        turtle.turnRight() -- Facing front
954
        placeSeal() -- 4
955
        turtle.turnLeft() -- Facing right
956
        goBack() -- F
957
        turtle.turnRight() -- Facing 2=front
958
        digForward() -- 3
959
        if level%8 then
960
          placeGlass() -- 3
961
        else
962
          goForward() -- 3
963
          placeSeal() -- 5
964
          goBack() -- F
965
        end
966
        turtle.turnLeft() -- Facing 2=right
967
        goBack() -- H
968
        if not(level%6 == 0 or (level-1)%6 == 0) then placeGlass() end -- F
969
        turtle.turnRight() -- Facing 2=front
970
        digForward() -- 2
971
        if level%8 then
972
          placeGlass() -- 2
973
        else
974
          goForward() -- 2
975
          placeSeal() -- 6
976
          goBack() -- H
977
        end
978
        turtle.turnRight() -- Facing 2=left
979
        digForward() -- J
980
        goForward() -- J
981
        digForward() -- K
982
        goForward() -- K
983
        placeSeal() -- 9
984
        placeLadderUp() -- K
985
        turtle.turnLeft() -- Facing front
986
        placeSeal() -- 8
987
        turtle.turnRight() -- Facing left
988
        goBack() -- J
989
        turtle.turnLeft() -- Facing 2=front
990
        digForward() -- 1
991
        if level%8 then
992
          placeGlass() -- 1
993
        else
994
          goForward() -- 1
995
          placeSeal() -- 7
996
          goBack() -- J
997
        end
998
        turtle.turnRight() -- Facing 2=left
999
        goBack() -- H
1000
        if not(level%6 == 0 or (level-1)%6 == 0) then placeGlass() end -- J
1001
        turtle.turnLeft() -- Facing 2=front
1002
      elseif (d == 3) then
1003
        placeSeal() -- 11
1004
        turtle.turnRight() -- Facing back
1005
        placeSeal() -- R
1006
        turtle.turnLeft() -- Facing left
1007
        turtle.turnLeft() -- Facing 3=front
1008
        digForward() -- L
1009
        if not(level%6 == 0 or (level-1)%6 == 0) then
1010
          placeGlass() -- L
1011
        else
1012
          goForward() -- L
1013
          turtle.turnRight() -- Facing left
1014
          placeSeal() -- 10
1015
          placeTorchUp()
1016
          turtle.turnLeft() -- Facing front
1017
          goBack() -- N
1018
        end
1019
        turtle.turnRight() -- Facing 3=left          
1020
      elseif (d == 4) then
1021
        placeSeal() -- X
1022
        turtle.turnLeft() -- Facing left
1023
        placeSeal() -- P
1024
        turtle.turnRight() -- Facing back
1025
        turtle.turnRight() -- Facing right
1026
        placeSeal() -- W
1027
        turtle.turnLeft() -- Facing back
1028
      end
1029
      -- Facing 1=right, 2=front, 3=left, 4=back
1030
      goBack() -- 1=A, 2=G, 3=M, 4=T
1031
      goBack() -- Start
1032
      turtle.turnRight() -- Facing 1=front, 2=left, 3=back, 3=right
1033
    end
1034
    for d=1,4 do
1035
      goForward()
1036
      placeChest() -- 1=B, 2=H, 3=N, 4=U
1037
      goBack() -- Start
1038
      placeChest() -- 1=A, 2=G, 3=M, 4=T 
1039
      turtle.turnRight() -- Facing 1=front, 2=left, 3=back, 3=right
1040
    end
1041
    print("Finished layer "..level)
1042
  end
1043
  -- Now put in an empty space below the last chest.
1044
  digDown()
1045
  turtle.down()
1046
  for d=1,4 do
1047
    digForward()
1048
    goForward() -- 1=A, 2=G, 3=M, 4=T
1049
    turtle.turnLeft()
1050
    digForward()
1051
    goForward()
1052
    placeSeal()
1053
    goBack()
1054
    turtle.turnRight()    
1055
    digForward()
1056
    goForward() -- 1=B, 2=H, 3=N, 4=U
1057
    turtle.turnLeft()
1058
    digForward()
1059
    goForward()
1060
    placeSeal()
1061
    goBack()
1062
    turtle.turnRight()    
1063
    turtle.turnRight()
1064
    digForward()
1065
    goForward() -- 1=C, 2=H, 3=N, 4=U
1066
    digForward()
1067
    goForward() -- 1=D, 2=H, 3=N, 4=U
1068
    placeSeal()
1069
    placeLadderUp()
1070
    goBack() -- 1=C
1071
    goBack() -- 1=B
1072
    turtle.turnLeft()
1073
    goBack() -- 1=A
1074
    goBack() -- 1=S
1075
    turtle.turnRight()
1076
  end
1077
  -- Now seal the bottom.
1078
  digDown()
1079
  turtle.down()
1080
  placeSealDown()
1081
  for d=1,4 do
1082
    digForward()
1083
    goForward() -- 1=A, 2=G, 3=M, 4=T
1084
    placeSealDown()
1085
    turtle.turnLeft()
1086
    digForward()
1087
    goForward()
1088
    placeSeal()
1089
    placeSealDown()
1090
    goBack()
1091
    turtle.turnRight()    
1092
    digForward()
1093
    goForward() -- 1=B, 2=H, 3=N, 4=U
1094
    placeSealDown()
1095
    turtle.turnLeft()
1096
    digForward()
1097
    goForward()
1098
    placeSeal()
1099
    placeSealDown()
1100
    goBack()
1101
    turtle.turnRight()    
1102
    turtle.turnRight()
1103
    digForward()
1104
    goForward() -- 1=C, 2=H, 3=N, 4=U
1105
    placeSealDown()
1106
    digForward()
1107
    goForward() -- 1=D, 2=H, 3=N, 4=U
1108
    placeSeal()
1109
    placeSealDown()
1110
    placeLadderUp()
1111
    goBack() -- 1=C
1112
    goBack() -- 1=B
1113
    turtle.turnLeft()
1114
    goBack() -- 1=A
1115
    goBack() -- 1=S
1116
    turtle.turnRight()
1117
  end
1118
  -- All down now go home.
1119
  if goToStart() then return true else return false end
1120
end
1121
function moveDownDigging()
1122
  if turtle.detectDown() then
1123
    if not hasPickAxe then
1124
      print("Turtle must have a pick axe to")
1125
      print("be able to dig.")
1126
      setStatus("unable to dig without pickaxe")
1127
      return false
1128
    end
1129
    if not turtle.digDown() then return false end
1130
  end
1131
  if not turtle.down() then return false end
1132
  return true
1133
end
1134
function digForward()
1135
  if turtle.detect() then
1136
    if not hasPickAxe then
1137
      print("Turtle must have a pick axe to")
1138
      print("be able to dig.")
1139
      setStatus("unable to dig without pickaxe")
1140
      return false
1141
    end
1142
    if not turtle.dig() then return false end
1143
  end
1144
  return true
1145
end
1146
function addInventoryLocation()
1147
  -- If a chest is found in inventory to be put away then create a new inventory location.
1148
  -- Go find the first inventory location without a chest.
1149
  if turtle.getItemCount(1) > 1 then
1150
    print("Adding inventory location.")
1151
    --print("Place glass blocks in slot 2.")
1152
    --print("Place torches in slot 3.")
1153
    --print("Place ladders in slot 4.")
1154
    --print("Place fill material in slot 6.")
1155
    --print("Press enter to continue:")
1156
    --io.read()
1157
    local level = 0
1158
    local location = 0
1159
    locDir = locDir + 1
1160
    changeOrientation(locDir)
1161
    if not moveDownDigging() then return false end
1162
    -- Now at floor level
1163
    level = level + 1
1164
    if not moveDownDigging() then return false end
1165
    -- Now at level above chests
1166
    level = level + 1
1167
    if not moveDownDigging() then return false end
1168
    -- Now at level of first chests
1169
    level = level + 1
1170
    locLevel = 1
1171
    while turtle.getItemCount(1) > 1 do
1172
      -- Find next Inventory location with no chest.
1173
       
1174
      print("Checking level "..locLevel)
1175
      for d=0,3 do
1176
        changeOrientation(invDir + d)
1177
        -- Check for an existing chest
1178
        if turtle.detect() then
1179
          turtle.select(1)
1180
          if not turtle.compare(1) then
1181
            while turtle.detect() do
1182
              turtle.select(2)
1183
              if not digForward() then return false end
1184
              sleep(.5)
1185
            end
1186
            turtle.forward()
1187
            while turtle.detect() do
1188
              turtle.select(2)
1189
              if not digForward() then return false end
1190
              sleep(.5)
1191
            end
1192
            turtle.back()
1193
          end
1194
        end
1195
        if not turtle.detect() then
1196
          turtle.forward()
1197
          while turtle.detect() do
1198
            turtle.select(2)
1199
            if not digForward() then return false end
1200
            sleep(.5)
1201
          end
1202
          turtle.select(1)
1203
          turtle.place()
1204
          turtle.back()
1205
          turtle.place()
1206
        end
1207
      end
1208
      if turtle.detectDown() then
1209
        turtle.select(2)
1210
        if not moveDownDigging() then return false end
1211
      else
1212
        if not turtle.down() then return false end
1213
      end
1214
      level = level + 1
1215
      locLevel = locLevel + 1
1216-
      refuel()
1216+
1217
    for l=1,level do turtle.up() end
1218
    level = 0
1219
    changeOrientation(unknownDir)
1220
    for s=1,maxSlot do
1221
      turtle.select(s)
1222
      if turtle.getItemCount(s) > 0 then turtle.drop() end
1223
    end
1224
    locDir = 0
1225
  end
1226
end
1227
-- Compare Inventory to contents of chest.
1228
function compareLocation(fillEmptyChests)
1229
  local emptyChestsFound = false
1230
	-- Set flag to indicate turtle is empty
1231
  turtle.select(1)
1232
  turtle.suck()
1233
  -- Only compare the slots if the chest wasn't empty.
1234
  local quantity = 0
1235
  if turtle.getItemCount(1) == 0 then
1236
    if fillEmptyChests then    
1237
      -- Put the next unidentified item in the slot to compare and place in the chest.
1238
      for s=2,maxSlot do
1239
        if turtle.getItemCount(s) > 0 then
1240
          turtle.select(s)
1241
          turtle.transferTo(1)
1242
          quantity = quantity + turtle.getItemCount(1)
1243
          break
1244
        end
1245
      end
1246
    else
1247
      emptyChestsFound = true
1248
      table.insert(emptyChests, currentLocation)
1249
    end
1250
  end
1251
  for s=2,maxSlot do
1252
    -- Are there any items in this slot?
1253
    if turtle.getItemCount(s) > 0 then
1254
      turtle.select(s)
1255
      if turtle.compareTo(1) then
1256
        -- The current item matches the contents of the chest.
1257
        quantity = quantity + turtle.getItemCount(s)
1258
        turtle.drop()
1259
        -- Subtract any that failed to be dropped.
1260
        quantity = quantity - turtle.getItemCount(s)
1261
        -- How do we detect that the chest is full?  You won't be able to drop it.
1262
      end
1263
    end
1264
  end
1265
  -- Now put the items back that were in slot 1.
1266
  -- If the chest is full the material will remain in slot 1 and needs to be moved out.
1267
  turtle.select(1)
1268
  turtle.drop()
1269
  -- Update inventory of location
1270
  local name, qty = getInventoryNameQty(currentLocation)
1271
  qty = qty + quantity
1272
  inventoryName[currentLocation] = name.."#"..qty
1273
  return emptyChestsFound
1274
end
1275
-- Put Inventory Away
1276
function putInventoryAway()
1277
  setStatus("putting inventory away")
1278
  -- Make sure there is nothing is slot 1.
1279
  if turtle.getItemCount(1) > 0 then
1280
    changeOrientation(unknownDir)
1281
    turtle.select(1)
1282
    turtle.drop()
1283
  end
1284
  -- First put any fuel away.
1285
  changeOrientation(fuelDir)
1286
  for s=2,maxSlot do
1287
    turtle.select(s)
1288
    if turtle.compareTo(fuelSlot) then turtle.drop() end
1289
  end
1290
  
1291
-- Check to see if any chests are in inventory
1292
  local chestFound = false
1293
  for s=2,maxSlot do
1294
    turtle.select(s)
1295
    if turtle.compare() then 
1296
      turtle.transferTo(1)
1297
      chestFound = true
1298
    end
1299
  end
1300
  
1301
  -- If there are chests then create new inventory locations with them.
1302
  changeOrientation(invDir)
1303
  if chestFound then addInventoryLocation() end
1304
  changeOrientation(invDir)
1305
  -- If there is still something in slot 1 then move it back to inventory chest.
1306
  if turtle.getItemCount(1) > 0 then turtle.drop() end
1307
  -- If there is still something in the turtle then put it away.
1308
  local emptyChestsFound = false, emptyChestLevel, emptyChestDir
1309
  emptyChests = {}
1310
	while not isTurtleEmpty() and gotoNextInventoryLocation() and not abortMission do 
1311
    emptyChestsFound = compareLocation(false)
1312
    if emptyChestsFound and emptyChestLevel == nil then
1313
      emptyChestLevel = locLevel
1314
      emptyChestDir = locDir
1315
    end
1316
  end
1317
  while not isTurtleEmpty() and #emptyChests > 0 do  
1318
    local chestLocation = emptyChests[1]
1319
    table.remove(emptyChests, 1)
1320
    print("Filling location "..chestLocation)
1321
    dirIdx = string.find(chestLocation, ",")
1322
    if dirIdx ~= nil then
1323
      emptyChestLevel = tonumber(string.sub(chestLocation, 1, dirIdx-1))
1324
      emptyChestDir = tonumber(string.sub(chestLocation, dirIdx+1))
1325
      gotoLocation(emptyChestLevel, emptyChestDir)
1326
      compareLocation(true)
1327
    end
1328
  end
1329
	if not goToStart() then return end
1330
  -- If there is inventory left then put it in the Unknown inventory chest
1331
	if not isTurtleEmpty() then emptyInventory() end
1332
end
1333
function putAwayInventory()
1334
	-- Is there inventory to put away
1335
	if not isTurtleEmpty() or loadInventory() then
1336
		putInventoryAway()
1337
    saveTable(inventoryName, "inventory")
1338
    return true
1339
  else
1340
    return false
1341
  end
1342
end
1343
 function findFuelChest()
1344
  -- Find first empty slot.
1345
  for s=1,maxSlot do
1346
    if turtle.getItemCount(s)==0 then
1347
      turtle.select(s)
1348
      break
1349
    end
1350
  end
1351
  testOK = false
1352
  for a=1,4 do
1353
    if turtle.suck() then
1354
      -- Was the fuel chest was found so we are in the correct location.
1355
      if turtle.compareTo(fuelSlot) then testOK = true end
1356
      turtle.drop()
1357
    end
1358
    if testOK then break else turtle.turnRight() end
1359
  end
1360
  return testOK
1361
end
1362
function powerUpChecks()
1363
  if turtle.getItemCount(fuelSlot) == 0 then
1364
    print("Place fuel in slot "..fuelSlot.." for fuel.")
1365
    while turtle.getItemCount(fuelSlot) == 0 do
1366
      sleep(10)
1367
    end
1368
  end
1369
  getPickAxeStatus()
1370
  --Move to the top
1371
  local x = 0
1372
  firstEmpty = false
1373
  while not turtle.detectUp() do
1374
    if turtle.up() then x = x + 1 end
1375
     
1376
    
1377
    if x > 10 and not turtle.detect() and firstEmpty then
1378
      -- We have travelled far enough
1379
      for z=1,x do
1380
         
1381
        turtle.down()
1382
      end
1383
      print("Can't locate ceiling.")
1384
      break
1385
    end
1386
    if not turtle.detect() then
1387
      firstEmpty = true
1388
    else
1389
      firstEmpty = false
1390
    end
1391
  end
1392
  print("Testing orientation.")
1393
  local testOK = "N"
1394
  if findFuelChest() then testOK = "Y" end
1395
  if string.upper(testOK) ~= "Y" then
1396
    local setupNeeded = ""
1397
    term.write("Create inventory chests? (Y/N):")
1398
    setupNeeded = string.upper(io.read())
1399
    if setupNeeded == "Y" then
1400
      hasPickAxe = true
1401
      local onFloor = "N"
1402
      while onFloor ~= "Y" do
1403
        term.write("At floor level? ('Y'/'U'p/'D'own):")
1404
        onFloor = string.upper(io.read())
1405
        if onFloor == "U" then turtle.up() end
1406
        if onFloor == "D" then turtle.down() end
1407
      end
1408
      if Initialize() then
1409
        if findFuelChest() then
1410
          testOK = "Y"
1411
          orientation = fuelDir
1412-
  if turtle.getFuelLevel() < 60 then
1412+
1413-
    print("Refueling.")
1413+
1414-
    refuel()
1414+
1415
      else
1416
        abortMission = true 
1417
      end
1418
    else
1419
      return false
1420
    end
1421
  end
1422-
    refuel()
1422+
1423
    turtle.turnLeft()
1424
    print("Facing fuel chest? (Y/N):")
1425
    testOK = string.upper(io.read())
1426
    if testOK == "Y" then
1427-
        refuel()
1427+
1428
      turtle.drop(1)
1429
    end
1430
  end
1431
  orientation = fuelDir
1432
  print("Found fuel chest")
1433
  -- Make sure nothing is in slot 1.  Bad things happen if that is so.
1434
  if turtle.getItemCount(1) > 0 then
1435
    changeOrientation(unknownDir)
1436
    turtle.select(1)
1437
    turtle.drop()
1438
  end  
1439
  changeOrientation(invDir)
1440
  inventoryName = loadTable("inventory")  
1441
  return true
1442
end
1443
function listenForMessages()
1444
  rednet.open("right")
1445
  while true do
1446
    setStatus("Listening")
1447
    local id, msg = rednet.receive(5)
1448
    if type(id) == "number" then
1449
      if id ~= storeKeeperID then table.insert(queue, msg) end
1450
    else
1451
      return false
1452
    end
1453
  end
1454
  rednet.close("right")
1455
end
1456
function setStatus(msg)
1457
  if rednet.isOpen("right") then
1458
    if orderComputer ~= nil then
1459
      rednet.send(orderComputer, msg)
1460
    else
1461
      rednet.broadcast(msg)
1462
    end
1463
  end
1464
end
1465
function returnItemToInventory(slot, level, dir)
1466
  local invLoc = level..","..dir
1467
  if turtle.getItemCount(slot) > 0 then
1468
    if gotoLocation(level,dir) then
1469
      turtle.select(slot)
1470
      local name, qty = getInventoryNameQty(invLoc)
1471
      qty = qty + turtle.getItemCount(slot)
1472
      inventoryName[invLoc] = name.."#"..qty
1473
      turtle.drop()
1474
    end
1475
  end
1476
end
1477
function countNew()
1478
  -- Count all of the inventory locations that don't have a quantity
1479
  local level = 1
1480
  local dir = 1  
1481
  while true do
1482
    local invLoc = level..","..dir
1483
    local name = inventoryName[invLoc]
1484
    if name ~= nil then
1485
      local qidx = string.find(name,"#")
1486
      if qidx == nil then countLocation(invLoc) end
1487
      if dir == 4 then
1488
        dir = 1
1489
        level = level + 1
1490
      else
1491-
  rednet.open(modemLocation)
1491+
1492
      end
1493
    end
1494
  end
1495
  goToStart()
1496
end
1497
function countAll()
1498
  -- Count all of the inventory locations that don't have a quantity
1499
  local level = 1
1500
  local dir = 1  
1501-
  rednet.close(modemLocation)
1501+
1502
    local invLoc = level..","..dir
1503
    if countLocation(invLoc) then
1504-
  if rednet.isOpen(modemLocation) then
1504+
1505
        dir = 1
1506
        level = level + 1
1507
      else
1508
        dir = dir + 1
1509
      end
1510
    else
1511
      break
1512
    end
1513
  end
1514
  goToStart()
1515
end
1516
function countLocation(invLoc)
1517
  -- Count item in invLoc.
1518
  print("Counting "..invLoc)
1519
  local totalQty = 0
1520
  local name, quantity = getInventoryNameQty(invLoc)
1521
  local quantity = 0  
1522
  local displayname = name
1523
  if name == "_" then displayname = "Unidentified" end
1524
  setStatus("counting "..displayname.." in location "..invLoc)
1525
  local idx = string.find(invLoc.."",",")
1526
  local level = tonumber(string.sub(invLoc,1,idx-1))
1527
  local dir = tonumber(string.sub(invLoc,idx+1))
1528
  if gotoLocation(level,dir) then
1529
    turtle.select(1)
1530
    while turtle.suck() and turtle.getItemCount(maxSlot)==0 do found = true end
1531
    for slot=1,maxSlot do
1532
      quantity = quantity + turtle.getItemCount(slot)
1533
    end
1534
    if quantity==0 then
1535
      inventoryName = tableRemoveKey(inventoryName,invLoc)
1536
    else
1537
      inventoryName[invLoc] = name.."#"..quantity
1538
    end
1539
    
1540
    setStatus(quantity.." "..displayname.." in location "..invLoc)
1541
    -- Now put it all back
1542
    for slot=1,maxSlot do
1543
      if turtle.getItemCount(slot) > 0 then
1544
        turtle.select(slot)
1545
        turtle.drop()
1546
      else
1547
        break
1548
      end
1549
    end
1550
  else
1551
    return false
1552
  end
1553
  return true
1554
end
1555
function fetchItem(command)
1556
  local invLoc = string.sub(command,6)
1557
  local quantity = 1
1558
  local quantityIdx = string.find(invLoc.."","-")
1559
  if quantityIdx ~= nil then
1560
    quantity = tonumber(string.sub(invLoc, quantityIdx+1))
1561
    invLoc = string.sub(invLoc,1,quantityIdx-1)
1562
  end
1563
  local item,qty = getInventoryNameQty(invLoc)
1564
  setStatus("Fetching "..item.." from "..invLoc)
1565
  print("Fetching "..quantity.." of "..item)
1566
  setStatus("fetching "..quantity.." of "..item)
1567
  depositInMasterChest(item, invLoc, quantity)
1568
end
1569
function tableRemoveKey(sourceTable, keyToRemove)
1570
  local newTable = {}
1571
  for key,value in pairs(sourceTable) do
1572
    if key ~= keyToRemove then newTable[key]=value end
1573
  end
1574
  return newTable
1575
end 
1576
function emptyInMasterChest(invLoc)
1577
  -- Locate item in inventoryName.
1578
  local found = false
1579
  local totalQty = 0
1580
  print("emptying location "..invLoc)
1581
  setStatus("emptying location "..invLoc)
1582
  found = true
1583
  local idx = string.find(invLoc.."",",")
1584
  local level = tonumber(string.sub(invLoc,1,idx-1))
1585
  local dir = tonumber(string.sub(invLoc,idx+1))
1586
  if gotoLocation(level,dir) then
1587
    turtle.select(1)
1588
    print("sucking from "..invLoc)
1589
    while turtle.suck() and turtle.getItemCount(maxSlot)==0 do found = true end
1590
    if turtle.getItemCount(maxSlot) == 0 then 
1591
      print("removing "..invLoc)
1592
      inventoryName = tableRemoveKey(inventoryName,invLoc)
1593
    end
1594
  else
1595
    setStatus("Unable to access location")
1596
    return false
1597
  end
1598
  if goToStart() then
1599
    if found then
1600
      if turtleInventory() == 0 then
1601
        setStatus("Location "..invLoc.." already empty.")
1602
      else
1603
        for s=1,maxSlot do
1604
          turtle.select(s)
1605
          turtle.dropUp()
1606
        end
1607
        setStatus("Location "..invLoc.." emptied.")
1608
      end
1609
      return true
1610
    end
1611
  end
1612
  setStatus("Unable to find location "..invLoc)
1613
  return false
1614
end
1615
function turtleInventory()
1616
  local qty = 0
1617
  for s=1,maxSlot do
1618
    qty = qty + turtle.getItemCount(s)
1619
  end
1620
  return qty
1621
end
1622
function getInventoryNameQty(invLocation)        
1623
  local name = inventoryName[invLocation]
1624
  local qty = 0
1625
  if name ~= nil then
1626
    local idx = string.find(name,"#")
1627
    if idx ~= nil then
1628
      qty = string.sub(name,idx+1)
1629
      if qty == nil then qty = 0 end
1630
      name = string.sub(name,1,idx-1)
1631
    end
1632
  else
1633
    name = "_"
1634
  end
1635
  return name,qty
1636
end
1637
function depositInMasterChest(item, invLoc, quantity)
1638
  -- Locate item in inventoryName.
1639
  local found = false
1640
  local totalQty = 0
1641
  for invLocation,value in pairs(inventoryName) do
1642
    local name, qty = getInventoryNameQty(invLocation)    
1643
    if name == item then
1644
      print("checking location "..invLocation)
1645
      setStatus("checking location "..invLocation)
1646
      found = true
1647
      local idx = string.find(invLocation.."", ",")
1648
      local level = tonumber(string.sub(invLocation,1,idx-1))
1649
      local dir = tonumber(string.sub(invLocation,idx+1))
1650
      if gotoLocation(level,dir) then
1651
        local prevQty = 0
1652
        turtle.select(1)
1653
        local firstSuck = true
1654
        totalQty = turtleInventory()
1655
        while totalQty < quantity do
1656
          if not turtle.suck() then
1657
            -- No more to suck
1658
            if firstSuck then tableRemoveKey(inventoryName,invLocation) end
1659
            break
1660
          else
1661
            totalQty = turtleInventory()
1662
            if totalQty > quantity then
1663
              -- We sucked more than we need
1664
              turtle.drop(totalQty - quantity)
1665
              break
1666
            elseif firstSuck then
1667
              -- We need to leave at least 1 per location.
1668
              turtle.drop(1)
1669
              firstSuck = false
1670
            end
1671
            qty = totalQty - prevQty
1672
            prevQty = totalQty
1673
            found = true
1674
          end
1675
        end
1676
        inventoryName[invLocation] = name.."#"..qty  
1677
        if totalQty == quantity then break end
1678
      else
1679
        setStatus("Unable to access location")
1680
        inventoryName = tableRemoveKey(inventoryName,invLocation)
1681
        return false
1682
      end
1683
      break
1684
    end
1685
  end
1686
  if goToStart() then
1687
    if found then
1688
      if turtleInventory() == 0 then
1689
        setStatus("only 1 "..item.." found.")
1690
      else
1691
        for s=1,maxSlot do
1692
          turtle.select(s)
1693
          turtle.dropUp()
1694
        end
1695
        setStatus("finished retrieving item "..item)
1696
      end
1697
      return true
1698
    end
1699
  end
1700
  setStatus("Unable to find item "..item)
1701
  return false
1702
end
1703
function getPickAxeStatus()
1704
  local fname = "hasPickAxe"
1705
  if fs.exists(fname) then
1706
    file = fs.open(fname, "r")
1707
    local frcd = file.readAll()
1708
    if frcd == "Y" then hasPickAxe = true else hasPickAxe = false end
1709
    file.close()
1710
  else
1711
    file = fs.open(fname, "w")
1712
    file.write("N")
1713
    file.close()
1714
    hasPickAxe = false
1715
  end
1716
end
1717
function getOrderComputer()
1718
  local fname = "InventoryControlID"
1719
  if fs.exists(fname) then
1720
    file = fs.open(fname, "r")
1721
    local frcd = file.readAll()
1722
    orderComputer = tonumber(frcd)
1723
    file.close()
1724
  else
1725
    print("Inventory Manager ID:")
1726
    orderComputer = tonumber(io.read())
1727
    file = fs.open(fname, "w")
1728
    file.write(orderComputer)
1729
    file.close()
1730
  end
1731
end
1732
function runQueue()
1733
  while true do
1734
    if #queue == 0 then
1735
      if not putAwayInventory() then
1736
         
1737
        setStatus("waiting")
1738
      end
1739
      return true
1740
    else
1741
      local command = queue[1]
1742
      print("Queue contains "..command)
1743
      table.remove(queue, 1)
1744
      if command == "identify" then
1745
        setStatus("Identify Acknowledged")
1746
        -- Identify items in unidentified locations
1747
        identifyInventory()
1748
        setStatus("finished")
1749
      elseif (command == "reportinventory") then
1750
        setStatus("Report Acknowledged")
1751
        reportInventory(orderComputer)
1752
      elseif (string.sub(command,1,5) == "fetch") then
1753
        setStatus("Fetch Acknowledged")
1754
        fetchItem(command)
1755
        saveTable(inventoryName, "inventory")
1756
        setStatus("finished")
1757
      elseif (string.sub(command,1,5) == "empty") then
1758
        setStatus("Empty Acknowledged")
1759
        local invLoc = string.sub(command,6)
1760
        setStatus("Emptying "..invLoc)
1761
        while inventoryName[invLoc] ~= nil do emptyInMasterChest(invLoc) end
1762
        saveTable(inventoryName, "inventory")
1763
        setStatus("finished")
1764
      elseif (string.sub(command,1,5) == "count") then
1765
        setStatus("Count Acknowledged")
1766
        local invLoc = string.sub(command,7)
1767
        if invLoc == "all" then
1768
          countAll()
1769
        elseif invLoc == "new" then
1770
          countNew()
1771
        else
1772
          countLocation(invLoc)
1773
          goToStart()
1774
        end
1775
        saveTable(inventoryName, "inventory")
1776
        setStatus("finished")
1777
      end
1778
    end
1779
  end
1780
end
1781
--------------------- Main Program ---------------------
1782
-- Check orientation. and move to start position.
1783-
        refuel()
1783+
1784
print("Computer ID: "..storeKeeperID)
1785
if not powerUpChecks() then return end
1786
print("Startup completed")
1787
getOrderComputer()
1788
while true do
1789
  if not listenForMessages() then
1790
    runQueue()
1791
  end
1792
end