Various bug fixes and refactorings