Refactor montecarlo code