@Override
  public ItemStack transferStackInSlot(EntityPlayer player, int slotID) {
    ItemStack stack = null;
    Slot currentSlot = (Slot) inventorySlots.get(slotID);

    if (currentSlot != null && currentSlot.getHasStack()) {
      ItemStack slotStack = currentSlot.getStack();
      stack = slotStack.copy();

      if (slotID == 2 || slotID == 4) {
        if (!mergeItemStack(slotStack, 5, inventorySlots.size(), true)) {
          return null;
        }
      } else if (ChargeUtils.canBeDischarged(slotStack)) {
        if (slotID != 1) {
          if (!mergeItemStack(slotStack, 1, 2, false)) {
            return null;
          }
        } else if (slotID == 1) {
          if (!mergeItemStack(slotStack, 5, inventorySlots.size(), true)) {
            return null;
          }
        }
      } else if (RecipeHandler.getChanceOutput(slotStack, false, tileEntity.getRecipes()) != null) {
        if (slotID != 0 && slotID != 1 && slotID != 2 && slotID != 3 && slotID != 4) {
          if (!mergeItemStack(slotStack, 0, 1, false)) {
            return null;
          }
        } else {
          if (!mergeItemStack(slotStack, 5, inventorySlots.size(), true)) {
            return null;
          }
        }
      } else if (slotStack.getItem() instanceof ItemMachineUpgrade) {
        if (slotID != 0 && slotID != 1 && slotID != 2 && slotID != 3) {
          if (!mergeItemStack(slotStack, 3, 4, false)) {
            return null;
          }
        } else {
          if (!mergeItemStack(slotStack, 5, inventorySlots.size(), true)) {
            return null;
          }
        }
      } else {
        if (slotID >= 5 && slotID <= 31) {
          if (!mergeItemStack(slotStack, 32, inventorySlots.size(), false)) {
            return null;
          }
        } else if (slotID > 31) {
          if (!mergeItemStack(slotStack, 5, 31, false)) {
            return null;
          }
        } else {
          if (!mergeItemStack(slotStack, 5, inventorySlots.size(), true)) {
            return null;
          }
        }
      }

      if (slotStack.stackSize == 0) {
        currentSlot.putStack((ItemStack) null);
      } else {
        currentSlot.onSlotChanged();
      }

      if (slotStack.stackSize == stack.stackSize) {
        return null;
      }

      currentSlot.onPickupFromSlot(player, slotStack);
    }

    return stack;
  }