improved performance by increasing the index of for-loops properly