Fix bug and add more debug output