major code cleanup. not complete, but a good first pass