Bugfixes and memory leak fixes