Refactoring done in theory. i.e. it compiles. of course everything explodse when running it