fixed some bugs, refactored some code and added comments