Some more refactoring to the code. Not yet compiled.