Manually merged #314 and #317, resolving errors if both merged

The changes in #314 break the memory leak fixes in #317, to ensure that all changes go in without problems I manually merged all the memory leak fixes in to #314.