Add logging

Code slightly restructured to make it log better