Fix PR #871

This one fixes #871, leaving as separate commits to review, I can squash when ready. Also @domcleals's commit was rebased to develop, that's why it has another hash. Test should be green now. Please review also other fixes.