Fix bugs in message tracking algorithm and clean up some code.