Rearrange code blocks and add comments