Fix some bugs and do some refactoring work.