Revert "simplified logic"

This reverts commit c638b61d9d3513529ce82ffb5f5eb748bcd50fb4.
And adds comments so it's easier to follow the logic.