This function makes me realize we're doing a lot of allocations and frees here. Is there any way to prevent that?