Debugging and logging fixes 

Lots of debugging fixes for running stuff under gdb. Make stderr output work properly. Include a lot more stuff under valgrind and 'make check-memory'.