Some refactoring in disconnect function