Code refactoring and added some comments