refactored upto loops to be Range#each (more readable)