Factor out ApplyMask