/*--------------------------------------------------------------------------
 *
 * 	You may freely copy, distribute, and reuse the code in this example.
 * 	SHL Systemhouse disclaims any warranty of any kind, expressed or  
 *	implied, as to its fitness for any particular use.
 *
 *
 *	BetterRealMutableArray
 *
 *	Inherits From:		NSMutableArray
 *
 *	Conforms To:		NSCopying, NSMutableCopying, NSCoding
 *
 *	Declared In:		BetterRealMutableArray.h
 *
 *
 *------------------------------------------------------------------------*/
#import "BetterRealMutableArray.h"
#import <appkit/appkit.h>

#define ARRAY_DEFAULT_CAPACITY 10




@implementation BetterRealMutableArray

/*--------------------------------------------------------------------------
 *	Allocing, initing, and deallocing
 *------------------------------------------------------------------------*/
+ arrayWithCapacity: (unsigned)aNumItems
{
	return [[[self alloc] initWithCapacity: aNumItems] autorelease];
}


- initWithCapacity:(unsigned)aNumItems
{
	unsigned iterator;

	array = NX_MALLOC(array, id, aNumItems);
	count = 0;
	capacity = aNumItems;
	
	for (iterator = 0; iterator < aNumItems; iterator++)
		array[iterator] = nil;
	
	return self;
}


- (void) dealloc
{
	NX_FREE(array);
	return [super dealloc];
}


/*--------------------------------------------------------------------------
 *	Immutable array primitives
 *------------------------------------------------------------------------*/
- (unsigned)count
{
	return capacity;
}

   
- objectAtIndex:(unsigned)index
{
	return array[index];
}	


/*--------------------------------------------------------------------------
 *	Mutable array primitives
 *------------------------------------------------------------------------*/
- (void)addObject:object
{
	int	iterator = 0;

	if (count == capacity) {
		NSLog(@"BetterRealMutable: Array full -- cannot addObject %s",
			[[(NSObject *)object description] cString]);
		return;
	}

	while (array[iterator] != nil) iterator++;

	array[iterator] = [object retain];
	count++;

	return;
}


- (void)replaceObjectAtIndex:(unsigned)index withObject:object
{
	if (index >= capacity) 
		return;

	if (array[index] == nil) count++;
	else [array[index] release];

	array[index] = [object retain];

	return;
}


- (void)removeLastObject
{
	unsigned	iterator = capacity-1;

	if (count == 0) return;


	while (array[iterator] == nil) iterator--;

	[array[iterator] release];
	array[iterator] = nil;
	count--;

	return;
}


- (void)insertObject:object atIndex:(unsigned)index
{
	if (index >= capacity) return;

	if (array[index] == nil) count++;
	else [array[index] release];

	array[index] = [object retain];
	return;
}


- (void)removeObjectAtIndex:(unsigned)index
{
	if (index >= capacity) return;

	if (array[index] != nil) count--;

	[array[index] release];
	array[index] = nil;

	return;
}


@end

