Big refactoring to make logging etc work