fix memory leak and refactoring