comments added fo readability. minor refactoring of code.