lots of refactoring changes. possibly some bugs.