Some optimizations + bug corrections