Supports multiple connections, refactored slightly