Fixed memory leak. Refactor loop method

Loop method is simpler, and closes the connection. Solving a potential memory leak by closing connection after opening it.