refactoring code
refactoring code and fixed some bugs