Resource leak fix, also cleanup.