Bug fixes and refactorizations