Adapted from Koen van Gilst’s original, with source on github