a lot of fixes, refactoring