Code refactoring, added some comments