Optimizations and bug fixes