Bug fix: Array index check
Optimize code