refactored the code.  It's still horribly ugly, but better