Fix bugs, improve error handling, allow debug output to be disabled.