optimizations and bug fixes