refactored and fix some bugs