Adds some refactorings and tests

Please merge this, so other can review these changes.