Fixes and optimizations cherry picked from BS12 master