Fix some bugs and do some refactor