added comments, many refactoring