some optimizations and fixes