Ugly for loop inside for loop