Improved simulation code to allow any number of segments