more optimizations and bug fixes