Refactor things and fix some tests