refactored and some comments added