refactoring and slight optimization with more comments.