Better debugging and some logic improvements