added comments and more refactoring