more reformating, still untested
changed the loop logic to use a single function...