extracting function factories to stop memory leaks (hopefully)