Fix some bugs and refactor code