Comments added. Minor refactoring to improve readability