Some optimizations and fixes