Many changes and fixes to remove leaks and return objects by reference