Refactored copy-pasted code, added comments.