Based upon Lexi's version with logging added.