Fix a memory leak plus other minor issues