refactored version(after comments)