a lot of fixes and refactoring