You could try checking the stack size with stack.stackSize, and check if it equals 1, otherwise subtract 1 from the stack, and add a new stack to the slot, then check if there is an empty slot and if there is, the repeat
Hope this helps, I'm still newbish to modding