Refactor code for simulation: add a function