Fix mask bug caused by index out of range