bug fixes and refactoring