Refactor, Fix, and Further hack Xenant's rewrite

My first hack toward this (major) refactor had a number of mistakes that were
(hopefully) corrected. I intend to now write tests for these (may require a bit
more refactoring...). But there is also probably a lot more that needs to be
done for this.