Consolidate code and remove resource leak.