Fixed memory leaks and dangling pointers, removed unsued functions, optimized a few functions and fixed the compiler warnings.