Connection pool close

As mentioned in a previous PR, here is the first attempt at implementing proper connection pool closing.
In the course of action I also did some refactorings (as per the commit messages).
Let me know what you think.