Bugs fixes and efficiency fixes