pulled out a Connection factory function
Pulled out some factories
Refactoring and error handling