#import <RCString.h>
/*
    Copyright (C) 1992. Bruce Ediger.

      This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU Library General Public License.
*/

//
// implementation of "character substitution and retrieval" methods
//

@implementation RCString (Characters)

- (int)retrieveCharacterAt:(int)index
{
	int iRetval = 0;

	if (index >= 0 && p && p->s && p->l > index)
		iRetval = p->s[index];

	return iRetval;
}

- substituteCharacter:(int)aChar at:(int)index
{
	if (index >= 0 && p && p->s && p->l - 1 > index) {
		if (p->n > 1)
			[self copyReference];
		p->s[index] = aChar;
	}
	return self;
}

- insertCharacter:(int)aChar at:(int)index
{
	if (index >= 0 && p && p->s && p->l - 1 > index) {
		char *bpNewString;
		if (p->n > 1)
			[self copyReference];
		bpNewString = malloc(p->l + 1);
		if (bpNewString) {
			bcopy(p->s, bpNewString, index);
			bpNewString[index] = aChar;
			bcopy(&p->s[index], &bpNewString[index + 1], p->l - index);
			free(p->s);
			p->s = bpNewString;
			++p->l;
		}
	}
	return self;
}

#ifndef INDEX
#define INDEX(a, b) index((a), (b))
#define RINDEX(a, b) rindex((a), (b))
#else
#define INDEX(a, b) strchr((a), (b))
#define RINDEX(a, b) strrchr((a), (b))
#endif

- (int)indexOfCharacter:(int)aChar
{
	char *bpTheChar;
	int   irRetval = -1;

	if (p && p->s) {
		bpTheChar = INDEX(p->s, aChar);
		if (bpTheChar)
			irRetval = (unsigned int)bpTheChar - (unsigned int)p->s;
	}

	return irRetval;
}

- (int)lastIndexOfCharacter:(int)aChar
{
	char *bpTheChar;
	int   irRetval = -1;

	if (p && p->s) {
		bpTheChar = RINDEX(p->s, aChar);
		if (bpTheChar)
			irRetval = (unsigned int)bpTheChar - (unsigned int)p->s;
	}

	return irRetval;
}

@end
