Hey, I threw together something that might help, the function returns the spaces that are free in the chest and the ones that have the same item or block whose stacksize is less then the max stack size for that item or block. with this it should be pretty easy to add an item to the correct slot in the chest.
public List<Integer> checkSpace(int x, int y, int z, ItemStack stack)
{
List<Integer> freeSpaces = new ArrayList();
try
{
TileEntity tempTile = worldObj.getBlockTileEntity(x, y, z);
if(tempTile!=null&&tempTile instanceof IInventory)
{
int i =0;
int num = 0;
boolean didFail = false;
while(!didFail)
{
try
{
((IInventory) tempTile).getStackInSlot(i);
i++;
num++;
}
catch(Exception e)
{
didFail = true;
}
}
for(int ix = 0; ix<num; ix++)
{
if(((IInventory) tempTile).getStackInSlot(ix)==null)
{
freeSpaces.add(ix);
}
else if (((IInventory) tempTile).getStackInSlot(ix).itemID == stack.itemID)
{
if(stack.stackSize+((IInventory) tempTile).getStackInSlot(ix).stackSize<stack.getItem().getItemStackLimit())
{
freeSpaces.add(ix);
}
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return freeSpaces;
}