Made masking lower and upper faster and less likely to result in out of
memory.