/*
 * Scrabbalize
 * Copyright (c) 2007, Blue Static <http://www.bluestatic.org>
 * 
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU 
 * General Public License as published by the Free Software Foundation; either version 2 of the 
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without 
 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with this program; if not, 
 * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
 */

#import "Word.h"

@interface Word (Private)
- (void)createAlphagram;
@end


@implementation Word

/**
 * Creates a new word object
 */
- (id)initWithWord:(NSString *)aWord
{
	if (self = [super init])
	{
		word = [aWord retain];
		[self createAlphagram];
	}
	return self;
}

/**
 * Destructor
 */
- (void)dealloc
{
	[word release];
	[alphagram release];
	[super dealloc];
}

/**
 * Initialize an object from a keyed archive
 */
- (id)initWithCoder:(NSCoder *)coder
{
	self = [super init];
	word = [[coder decodeObjectForKey:@"KAWord"] retain];
	alphagram = [[coder decodeObjectForKey:@"KAAlphagram"] retain];
	return self;
}

/**
 * Encodes an object for serialization in a keyed archiver
 */
- (void)encodeWithCoder:(NSCoder *)coder
{
	[coder encodeObject:word forKey:@"KAWord"];
	[coder encodeObject:alphagram forKey:@"KAAlphagram"];
}

/**
 * Returns the word
 */
- (NSString *)word
{
	return word;
}

/**
 * Gets the length of the word
 */
- (int)length
{
	return [word length];
}

/**
 * Returns the alphagram
 */
- (NSString *)alphagram
{
	return alphagram;
}

/**
 * Generates the alphagram for the word
 */
- (void)createAlphagram
{
	char *str = (char *)[word UTF8String];
	
	int j;
	for (int i = 1; i < [word length]; i++)
	{
		char temp = str[i];
		for (j = i; j > 0 && temp < str[j - 1]; j--)
		{
			str[j] = str[j - 1];
		}
		str[j] = temp;
	}
	
	alphagram = [[NSString stringWithUTF8String:str] retain];
}

/**
 * Description method
 */
- (NSString *)description
{
	return [NSString stringWithFormat:@"<Word:%@/%@>", word, alphagram];
}

@end
