Code cleanup and add reconnect logic