First pass of refactoring. Everything moved around for neater code.