Reorganizing the code to improve clarity

No changes to behavior in this commit.