refactored some code, fixed few bugs