Refactor code within simulation.  Grouped local functions with main function.