Big refactoring commit

Too much to describe.