Quick code cleanup and fixed some memory leaks