Refactoring, fix bugs