Rewritten the connection code for easier editting