I didn't add docstring because it is very technical code and I don't understand what is being implemented.
The code has not yet been cleaned up, just moved.