Fix some bugs and refactor