Major refactoring

Changed variable names to be more semantic. Rewrote reused code to refer to variables. Reordered functions.