Cleanup: Memory leak fixes and program-flow cleanup