Fix several bugs, more debug messages, code tweak