cleanup and stats function