rearrange code to handle refcount correctly