added comments and did some minor refactoring of code