Lots of refactoring and improvements

Sorry for the messy commit messages. I'll make more of an effort if anyone else was contributing to the project.