some bug fixes and refactoring