This looks good, but it should be implemented in Cython.