more refactoring, things still quite buggy...