fix memory leaks and few bugs