Fixed the most intense memory leaks. Fixed the error on exit.