commenting and minor refactoring for clarity