lots of fixes and little refactoring