multiple optimizations and bug fixes