minor bug fixes and code refactoring