refactoring, fix some logical bugs