Fix some bugs and leaks.