Fix few memory leaks and other bugs.