Refactoring, bug fixes