Fix memory leaks and create working integration test