A lot of fixes and refactoring