added comments and subtle refactoring