Fix a few bugs and memory leak.