Added proper support for disconnecting

Also slightly improved performance