many optimizations and fixes