Big refactor

And candidate for the best commit message ever.