All of this could be fixed with a few comments explaining how the code works and why certain things are done a particular way. But somehow that is hard to do.