Separate output generation from the loop iteration logic.

Currently the enterprise grade stuff for generating output is heavily mixed with enterprise grade for running the loop. This makes code much harder to maintain. Also factories are persisted long after they are not needed anymore which is likely to cause JVM memory issues in widely used enterprise Java implementations.

This fixes it all - generation is factored out and factories are only persisted while they are needed.