refactor and fix bugs