
synth = peripheral.wrap('right')
pur = peripheral.wrap('left')
chest = peripheral.wrap('top')

delay = 30

function most_damaged(chest)
    local stack
    local max_damage = 0
    local index
    local name
    for i=1,chest.getInventorySize() do
        stack = chest.getStackInSlot(i)
        if stack and stack.dmg > max_damage then
            --print(i..': '..stack.name..' ('..tostring(16-stack.dmg)..'/16)')
            max_damage = stack.dmg
            name = stack.name
            index = i
        end
    end
    if index then
        print('Most damaged: '..name..' ('..tostring(16-max_damage)..'/16) in slot '..tostring(index))
    else
        print('All is fine...')
    end
    return index
end

while true do
    stack = synth.getStackInSlot(3)
    if stack == nil then
        print('Synthesizer is empty...')
        index = most_damaged(chest)
        if index then
            print('Trying to fill the serum up...')
            chest.pushItem('down', index, 1)
            turtle.turnRight()
            turtle.drop()
            turtle.turnLeft()
            -- synth.pullItem('north', 1, 1)
        end
    elseif stack.dmg > 0 then
        print(stack.name..' still filling up  ('..tostring(16-stack.dmg)..'/16)')
    else
        print(stack.name..' filled up, moving to purifier...')
    
    
        pstack = pur.getStackInSlot(3)
        if pstack ~= nill then
            print('Moving '..pstack.name..' from purifier...')
            r = pur.pushItem('south', 3, 1)
            turtle.dropUp()
        else
            print('Purifier is available...')
        end
    
        synth.pushItem('north', 3, 1)
        
        turtle.turnLeft()
        turtle.drop()
        turtle.turnRight()
        -- pur.pullItem('south', 1, 1)
    
        index = most_damaged(chest)
        if index then
            print('Trying to fill the serum up...')
            chest.pushItem('down', index, 1)
            turtle.turnRight()
            turtle.drop()
            turtle.turnLeft()
            -- synth.pullItem('north', 1, 1)
        end
    
    end

    os.sleep(delay)

end




