I'm going through the code now and I think it needs major refactoring to make it readable. I'll open smaller sub-issues related to this.
These will require quite a bit of effort, so I think it makes sense to keep these in mind and fix them bit by bit as we go on.