Fixed the connection leaka nd cleaned up the code a little bit