Refactored and added comments