Initial refactoring, untested and has todos