corrected some bugs, refactored the logic