Add logging and fix some bugs.