This loop should be implemented in Cython.