Port stuff over from the original Gist