Resurrect ref counting code. Fixes crash, but test still fails