Added loops to eliminate repetitions, seems to work fine