fix bugs and refactoring