Refactored simulation code