Fix resource leak in cleanup code and refactor API