added comments, and minor refactoring