simplifying loops

Moved most of the details in the loops into a separate program and
restructured some of the code to make this possible.