SG_REF before SG_UNREF

I know, it's a lot of changes even in critical places. But I think it's worth it: if we can avoid **trivial** errors (and frustration ;)) so easy, we should do it.

@sonney2k, @karlnapf: It's related to #1562, so you may be interested in this one as well.