Fix a reference counting bug in the rewriter and add tracing and debugging.