refactored code and fixed some errors.