nine: make proper internal reference counting

Also fix related memory leaks