upgraded cleanup function