Code Optimizations and fixes