Made some further optimizations and fixed some bugs of previous ones.