Stable -- refactor for testing. Moved functions. Changed logging.