Fixed allocation errors. Fixed some memory leaks.