a few bug fixes and refactoring