Various bug fixes

* Fixes lots of memory leaks
* Fixed lots of NULL pointer dereferences
* Fixes other issues found by clang scanbuild