Add logging and some refactoring.