bug fixes and minor refactoring