Fixing reference counting issues Dmytro and Rahul reported.