Memory leak fixes (mostly) in production code + some refactoring