replaced copied code with for loop to use common code