bugfixes, a lot of internal refactoring.