Big refactoring (I know, not a very useful commit message)