optimizations and bug fix