Fix bugs + refactor.