Refactoring; bug fixes