Complete refactoring. (Not working currently!)