Code refactoring and added comments