/*
 *	Filename: NSString_ext.m
 *	Created : Mon Jan 20 15:28:52 1997
 *	Author  : Vince DeMarco
 *	LastEditDate Was "Mon Jan 20 17:16:20 1997"
 */

#import "NSString_ext.h"
#import <Foundation/Foundation.h>

@implementation NSString (RegexStringExtensions)

+ (NSString *)stringWithFormat:(NSString *)format array:(NSArray *)data
{
    return [[[self alloc] initWithFormat:format array:data] autorelease];
}

- (id)initWithFormat:(NSString *)format array:(NSArray *)data
{
    NSRange searchRange = NSMakeRange(0,[format length]);
    NSRange percentRange;

    percentRange = [format rangeOfString:@"%" options:0 range:searchRange];

    if (percentRange.length > 0){
	NSMutableString *buffer		     = [format mutableCopy];
	int              locationOffset	     = 0;

	while (percentRange.length == 1){

		/* Check back one character if the current character has been escaped if it has ignore it */
	    if ((percentRange.location > 0)
		&& ([format characterAtIndex:percentRange.location - 1] == (unichar)'\\')){
		    /* Ignore it */
	    }else{
		    /* It might be a subexpression format sequence */
		if (percentRange.location + 1 < NSMaxRange(searchRange)){
		    unichar digit = [format characterAtIndex:percentRange.location + 1];

		    if ((digit >= (unichar)'0') && (digit <= (unichar)'9')){
			unsigned subexpIndex = digit - (unichar)'0';

			if (subexpIndex == 0){
			    [buffer replaceCharactersInRange:NSMakeRange(percentRange.location + locationOffset, 2)
				    withString:[NSString concatenateStringsFromArray:data]];
			} else {
			    if (subexpIndex <= [data count]){
				[buffer replaceCharactersInRange:NSMakeRange(percentRange.location + locationOffset, 2)
					withString:[data objectAtIndex:subexpIndex - 1]];
				locationOffset += [[data objectAtIndex:subexpIndex - 1] length] - 2;
				percentRange.length = 2;
			    }
			}
		    }
		}

	    }
	    searchRange  = NSMakeRange(NSMaxRange(percentRange), NSMaxRange(searchRange) -
				       NSMaxRange(percentRange));
	    percentRange = [format rangeOfString:@"%" options:0 range:searchRange];
	}
	return buffer;
    }else{
	return nil;
    }
}

+ (NSString *)concatenateStringsFromArray:(NSArray *)array
{
    NSEnumerator    *enu;
    NSString        *obj;
    NSMutableString *result;

    result = [[[NSMutableString allocWithZone:[self zone]] init] autorelease];
    enu    = [array objectEnumerator];

    while((obj = [enu nextObject])){
	[result appendString:obj];
    }
    return result;
}

@end
