// 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 "OFTrieNode.h"

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

RCS_ID("$Header: /Network/Developer/Source/CVS/OmniGroup/OmniFoundation/DataStructures.subproj/OFTrieNode.m,v 1.5 1999/03/30 21:25:41 kc Exp $")

@implementation OFTrieNode

- (void)addChild:aChild withCharacter:(unichar)c;
{
    if (count) {
        unsigned int i;
        unsigned index = trieFindIndex(self, c);
	
	if (index < count && characters[index] == c) {
	    [children[index] release];
	} else {
            NSZone *myZone = [self zone];
            characters = (unichar *)NSZoneRealloc(myZone, characters, sizeof(unichar)*(count+1));
            children = (id *)NSZoneRealloc(myZone, children, sizeof(id)*(count+1));
	    for (i = count; i > index; i--) {
		characters[i] = characters[i-1];
		children[i] = children[i-1];
	    }
	    characters[index] = c;
	    count++;
	}
	children[index] = [aChild retain]; 
    } else {
        NSZone *myZone = [self zone];
        characters = (unichar *)NSZoneMalloc(myZone, sizeof(unichar));
        children = (id *)NSZoneMalloc(myZone, sizeof(id));
	*characters = c;
	*children = [aChild retain];
	count = 1;
    }
}

- (void)dealloc
{
    unsigned int i;
    NSZone *myZone = [self zone];

    for (i = 0; i < count; i++)
	[children[i] release];
    NSZoneFree(myZone, characters);
    NSZoneFree(myZone, children);
    [super dealloc];
}

- (NSMutableDictionary *)debugDictionary;
{
    NSMutableDictionary        *debugDictionary;

    debugDictionary = [super debugDictionary];
    if (count) {
	NSArray *kids = [[NSArray alloc] initWithObjects:children count:count];

	[debugDictionary setObject:kids forKey:@"children"];
	[kids release];
	[debugDictionary 
	    setObject:[NSString stringWithCharacters:characters length:count] 
	    forKey:@"keys"];
    }
    return debugDictionary;
}

@end
