Final bug fixes and refactorings