This code is difficult to understand, consider breaking into multiple passes, or writing debug assertions before and after so the intended behaviour is clearer