beautifully refactored (with the help of Stephen)