This code is a bit complex, but we can add comments later. LGTM.