So far I could follow along. The remaining logic deserves more comments. Even though its ported from the existing implementation...