fix bugs and refactor codes