Refactoring source code and add reconnect functionality