Fixed issue with unwrap and shared state refcounting. Fixes #1037.