pulled out for loop used multiple times and made it a function