reorganize one iteration

move all the loops to separate functions

add a whole bunch of tests

use c++ range based for loops