Fix some bugs and add more debugging output
