Resource clean up unified in functions to avoid accidental leaks.