Switched to recursive maintenance function to avoid code duplication