Refactoring, minor bug fixes