Merged imlucas' fix for #512