Refactor the statistics gathering code in run.ml