Fix bugs and add debugging code