lots of refactoring+bugfixes
code cleanup