Code Refactor

This looks like a huge number of changes, but it's mostly just moving things around for readability, changing a few function declarations, and very few actual code changes.