Replace duplicate code with for loop, fix minor errors