refactored code, fixed some bugs