Ported code from Pull request fog/fog#3187