optimized all of the for-loops