Adapted Python code to 8985cf244b2f3ff531c26bd44d413a295da9436f
Speed improvements