Fixed memory leaks. Not yet tested