fix memory leak and improve code flow