moved inner loops to cython