Moved connection logic into its own function.

Added comments.