This adds a long comment explaining the algorithm and implementation choices by building it up step by step in Python. Comments in the code are also reworked/added, with references to the long explanation.
Refactored by: Pieter Wuille <pieter@wuille.net>