A lot of code cleanup and fixed memory leaks