Fixes #133 (closed)
Cherry-picked from #131 which has more test coverage (that is not easily cherry-picked).