Refactor the reference counting system.

Add a function unref() that deletes the object if its refcount becomes
zero.