lots of refactoring and bug fixes