some refactoring, and bug fixes