applyMask function