bug fixes and lots of refactoring