Reworked some functions for readability. Added some basic comments, fixed formatting, refactored for efficiency where possible.