Refactor and fix bugs