There are quite a few details in that function and many ways to get it wrong. It’s a bit hard to diagnose just from the wrong answer. The best way to debug is to start by reading this post from mrgransky that describes in words the details of how the algorithm works.