Clean up code and fix memory leaks