fix potential crash, speedups, and do copy back the mask