Refactor and fix bugs.