Added proper comments and refactored code