/*****************************************************************************

	Replac()

	This function is the "replacement" part of the FS, FN, F_ and FC
commands.  It replaces the found string with the replacement string.

*****************************************************************************/

#include "ZPort.h"		/* define portability identifiers */
#include "DefChars.h"		/* define identifiers for characters */
#include "DefTeco.h"		/* define general identifiers */

extern	DEFAULT	Search();	/* top level search */
extern	VOID	ZCpyBl();	/* copy block of memory */

EXTERN	char	*ArgPtr;	/* beginning of text argument to command */
EXTERN	char	*GapBeg;	/* edit buffer gap beginning */
EXTERN	char	*GapEnd;	/* edit buffer gap end */
EXTERN	char	*CBfPtr;	/* pointer into command buffer */
EXTERN	BOOLEAN	Matchd;	/* indicates successful search */
EXTERN	LONG	RefLen;		/* returned by ^S command */


DEFAULT Replac()
{
#if DEBUGGING
DbgInd+=2;if(DbgLvl>=2){DbgMsg();DbgDBf("Replac: called.\015\012");DbgROf();}
#endif

	if (Search(YES) == FAILURE)
#if DEBUGGING
{if(DbgLvl>=1)
{DbgMsg();DbgDBf("Replac: returning FAILURE.\015\012");DbgROf();}DbgInd-=2;
#endif
		return(FAILURE);
#if DEBUGGING
}
#endif

	if (Matchd)				/* if successful search */
		{
		GapBeg += RefLen;		/* delete found string */
		RefLen = ArgPtr - CBfPtr;	/* length of replacement */
		if ((GapEnd-GapBeg) < -RefLen)	/* if gap too small */
			if (GroEBf(-RefLen) == FAILURE)
#if DEBUGGING
{if(DbgLvl>=2)
{DbgMsg();DbgDBf("Replac: returning FAILURE.\015\012");DbgROf();}DbgInd-=2;
#endif
				return(FAILURE);
#if DEBUGGING
}
#endif
		ZCpyBl(-RefLen, ArgPtr, GapBeg);/* put in the replacement */
		GapBeg -= RefLen;		/* adjust gap beginning */
		}

#if DEBUGGING
if(DbgLvl>=2)
{DbgMsg();DbgDBf("Replac: returning SUCCESS.\015\012");DbgROf();}DbgInd-=2;
#endif
	return(SUCCESS);
}
