This revision addresses Jani's comments. It removes some const-stripping casts (at the cost of dropping a const from the API), fixes a delayed free, and cleans up some aesthetics.