Fixes and optimizations cherry picked from BS12