Major code cleanup, hopefully without introducing new bugs.