some bugfixes and lots of refactoring for great good