More bug fixes and refactorings