Finished refactoring (and fixing stupid bugs).