A lot of fixes and initial refactoring