Finally fixed the problems when closing a connection, and tidied up the module