Fix bugs and add debug traces