more fixes
more refactoring and minor optimizations