Improved masking function.