Misc bugfixes and debug logging