much cleanup and helper functions