fix bugs and refactor