Unwind this logic a bit.

Change-Id: I320b28fb319b42eeae7cada31b6f27f9e342db15
Annotate the code a little more, to make it easier to follow.

Change-Id: Iefc61fdc132a18e73b0136f0248d69ab9e07a5e8