WIP, cleanup.  refactoring by splitting huge stuff into smaller
functions.  the code has gotten hard to read.
forgot to add this earlier