Reorganized functions and commented them.

Reordered functions to have a more logical flow when reading from top to bottom.
Renamed confusing variables.
Commented each function to explain how they are used.