Fixed some bugs and subtle memory leaks that only occur during rare paths of execution