COMMAND(REPLACE)
#if NOTIMP_REPLACE
NOTIMPLEMENTED;
#else
NODE nItem;
VARIABLE Op1,Op2,Op3,Op4,Op5;
long lRepetitions;
long lCalculatedRepetitions;
int ReplaceAll;
long l_start,lStart,lLength,lSearchLength,lReplaceLength,lResult;
char *r,*s,*q,*w;
int iCase = OPTION("compare")&1;
/* this is an operator and not a command, therefore we do not have our own mortal list */
USE_CALLER_MORTALS;
/* evaluate the parameters */
nItem = PARAMETERLIST;
/* this is the base string that we are searching in */
Op1 = _EVALUATEEXPRESSION(CAR(nItem));
ASSERTOKE;
if( memory_IsUndef(Op1) ){
RESULT = NULL;
RETURN;
}
Op1 = CONVERT2STRING(Op1);
nItem = CDR(nItem);
lLength = STRLEN(Op1);
r = STRINGVALUE(Op1);
/* this is the string that we search to replace */
Op2 = _EVALUATEEXPRESSION(CAR(nItem));
ASSERTOKE;
if( memory_IsUndef(Op2) ){
RESULT = NULL;
RETURN;
}
Op2 = CONVERT2STRING(Op2);
nItem = CDR(nItem);
lSearchLength = STRLEN(Op2);
s = STRINGVALUE(Op2);
/* this is the string that we put into the place of the searched string */
Op3 = _EVALUATEEXPRESSION(CAR(nItem));
ASSERTOKE;
if( memory_IsUndef(Op3) ){
RESULT = NULL;
RETURN;
}
Op3 = CONVERT2STRING(Op3);
lReplaceLength = STRLEN(Op3);
nItem = CDR(nItem);
w = STRINGVALUE(Op3);
Op4 = NULL;
if( nItem ){
Op4 = EVALUATEEXPRESSION(CAR(nItem));
nItem = CDR(nItem);
ASSERTOKE;
}
if( memory_IsUndef(Op4) ){
lRepetitions = 0;
ReplaceAll = 1;
}else{
lRepetitions = GETLONGVALUE(Op4);
ReplaceAll = 0;
}
if( lRepetitions < 0 )lRepetitions = 0;
Op5 = NULL;
if( nItem ){
Op5 = EVALUATEEXPRESSION(CAR(nItem));
nItem = CDR(nItem);
ASSERTOKE;
}
if( memory_IsUndef(Op5) )
l_start = 1;
else{
l_start = GETLONGVALUE(Op5);
}
if( l_start < 1 )l_start = 1;
lStart = l_start;
/* first calculate the repeat actions */
lCalculatedRepetitions = 0;
while( lStart-1 <= lLength - lSearchLength ){
if( ! SUBSTRCMP(r+lStart-1,s, lSearchLength,iCase ) ){
lCalculatedRepetitions++;
lStart += lSearchLength;
}else lStart ++;
}
if( ! ReplaceAll && lCalculatedRepetitions > lRepetitions )lCalculatedRepetitions = lRepetitions;
/* calculate the length of the new string */
lResult = STRLEN(Op1) + lCalculatedRepetitions * (lReplaceLength-lSearchLength);
/* allocate space for the result */
RESULT = NEWMORTALSTRING(lResult);
ASSERTNULL(RESULT)
/* perform the replacements */
lStart = l_start;
q = STRINGVALUE(RESULT);
if( lStart > 1 ){
q+=lStart-1;
}
while( lStart <= lLength ){
if( lCalculatedRepetitions && ! SUBSTRCMP(r+lStart-1,s, lSearchLength,iCase ) ){
q += lReplaceLength;
lStart += lSearchLength;
lCalculatedRepetitions--;
}else{
*q++ = r[lStart-1];
lStart ++;
}
}
#endif
END