One cleanup and two fixes; one use-after free, and another state tracking fix. See individual commits.