fix resource leaks and other bugs