more fixes and refactoring... seems to work well