refactored code and added comments.
merged conflict