refactored code to some extent