Some rearanging, some fixing up here and there

This pull request has mostly untested commits to tidy up the code and make it more stable. I'll be pushing more commits to fix some issues later on.