Quite rough refactoring but ok for now