refactored code and fixed bugs