A lot of fixes and refactorings