Fixed a bug of array index out of bounds, and removed unneccessary variables