Initial attempt to clean up / refactor some of the code to make it not make your head want to explode when looking at it :/