Fix bugs and refactoring