bug fixes, and small refactoring