small optimizations and bug fix