I took this from http://stackoverflow.com/a/3455340 and the previous PR (#251)