Fixed a lot of memory leaks and improved error handling