This is a rebased version of #213. I've reworked the commit to shorten it, but the original author is the same.