bugfixes, refactoring, some testing