refactored and added comments