Fix bugs and refactor.