// Copyright 1997-1999 Omni Development, Inc.  All rights reserved.
//
// This software may only be used and reproduced according to the
// terms in the file OmniSourceLicense.html, which should be
// distributed with this project and can also be found at
// http://www.omnigroup.com/DeveloperResources/OmniSourceLicense.html.

#import "OFObject.h"

#import <Foundation/Foundation.h>
#import <Foundation/NSDebug.h>
#import <OmniBase/OmniBase.h>

#import "OFNull.h"
#import "OFSimpleLock.h"
#import "NSDebug-OFExtensions.h"

RCS_ID("$Header: /Network/Developer/Source/CVS/OmniGroup/OmniFoundation/OFObject.m,v 1.21 1999/03/30 21:25:31 kc Exp $")

@implementation OFObject

static OFSimpleLockType retainLock;

#ifdef DEBUG
#define SaneRetainCount 1000000
#define FreedObjectRetainCount SaneRetainCount + 234567;
#endif

+ (void)initialize;
{
    static BOOL initialized = NO;

    [super initialize];
    if (initialized)
	return;
    initialized = YES;

    OFSimpleLockInit(&retainLock);
}

- (void)dealloc;
{
#ifdef DEBUG
    retainCount = FreedObjectRetainCount;
#endif
    [super dealloc];
}

- (unsigned int)retainCount;
{
    return retainCount + 1;
}

- retain;
{
    OFSimpleLock(&retainLock);
#ifdef DEBUG
    if (retainCount > SaneRetainCount) {
        [NSException raise:@"RetainInsane"
                    format:@"Insane retain count! count=%d self=0x%x",
                           retainCount, (unsigned int)self];
    }
#endif

    if (NSKeepAllocationStatistics) {
        // Repord our allocation statistics to make OOA and oh happy
        NSRecordAllocationEvent(NSObjectInternalRefIncrementedEvent, self, NULL, NULL, NULL);
    }
    retainCount++;
    OFSimpleUnlock(&retainLock);
    return self;
}

- (void)release;
{
    OFSimpleLock(&retainLock);

    if (NSKeepAllocationStatistics) {
        // Report our allocation statistics to make OOA and oh happy
        NSRecordAllocationEvent(NSObjectInternalRefDecrementedEvent, self, NULL, NULL, NULL);
    }

    if (retainCount == 0) {
        OFSimpleUnlock(&retainLock);
	[self dealloc];
    } else {
#ifdef DEBUG
        if (retainCount > SaneRetainCount) {
            [NSException raise:@"RetainInsane" format:@"Insane retain count! count=%d self=0x%x", retainCount, (unsigned int)self];
	}
#endif
	retainCount--;
        OFSimpleUnlock(&retainLock);
    }
}

@end
