bug fixes, some refactoring