rebasing #1184 onto the Nov 2014 version

since #1184 wasn't merged and rebasing was too much work I recreated the patch.
Is there any way to simplify this?