add comments and minor refactoring