Refactor connect logic