Several optimizations and bug fixes