Fix some bugs and refactoring.