c = peripheral.wrap('bottom')

t = c.getStackInSlot(2)

jars = {}
chest_contents = {}
slot2aspect = {}

function scan_chest()
    local is = c.getInventorySize()
    for i = 1,is do
        s = c.getStackInSlot(i)
        if s then
            c.pushItem('up', i, 1)
            turtle.place()
            t = scan_jar()
            print('Scanned a jar with '..t.quantity..' of '..t.name)
            jars[t.name] = {}
            jars[t.name].quantity = t.quantity
            jars[t.name].slot = i
            chest_contents[i] = t
            turtle.dig()
            c.pullItemIntoSlot('up', 1, 1, i)
        end
    end    
end

function scan_jar()
    j = peripheral.wrap('front')
    t = j.getAspects()
    return t[1] -- quantity, name
end

function deploy_aspects(aspects)
    if #aspects > 5 then
        error('Sorry, I cannot deploy more than 5 aspects')
    end
    for i = 1, #aspects do
        local aspect = aspects[i]
        if not jars[aspect] then
            error('Sorry, missing '..aspect)
        end
        slot = jars[aspect].slot
        c.pushItem('up', slot, 1)        
        if i < 5 then
            turtle.place()
            turtle.turnRight()
        else
            turtle.placeUp()
        end
    end
end

function undeploy()
    local need_scan = true
    for i = 1, 5 do
        if i < 5 then
            digf = turtle.dig
            dir = 'front'
        else
            digf = turtle.digUp
            dir = 'top'
        end
        print(i)
        print(peripheral.getType(dir))
        if peripheral.getType(dir) == 'tilejarvoid' then
            if need_scan then
                -- don't keep track of jar, we'll rescan
                digf()
                turtle.dropDown()
            else
                -- keep track of jar carefully
                j = peripheral.wrap(dir)
                t = j.getAspects()
                target_slot = jars[t.name].slot
            end            
        end
        turtle.turnRight()
    end
    if need_scan then scan_chest() end
end

undeploy()
deploy_aspects({'Humanus', 'Instrumentum', 'Machina'})