
#ifdef TPLTER

CMD =
    Replace;

VERSION = "1.0";

DESCRIPTION = {{
	FILTER
	    Replaces Strings from input(files) to output;
	    should also handle most binary files

	OPTIONS
	    FIND/A	  - the string to find (no wildcards yet)
	    REPLACE/A	  - the string to replace the findstr with
	    //BUFFERLEN/N/K - the size of the read buffer

	OUTPUT
	    input w/ <find> replaced by <replace>
}};

BUGS = {{
	fails, if the searchstring is positioned
	over the end of the buffer
	e.g.
	> echo 123--67-- | Replace -- ** BUFSIZE 4 in:
	123--67--
}};

EXAMPLES = {{
	> echo 123--67-- | Replace -- ** in:
	123**67**
}};

HISTORY = {{
	13-02-95 b_noll created
	16-02-95 b_noll created .data file
	23-02-95 b_noll updated documentation
	23-02-95 b_noll enabled builtins buffer support of gen.c.tplt
	26-02-95 b_noll added breakcheck
}};

TEMPLATE =
    //"FIND/A,REPLACE/A,BUFFERLEN/N/K";
    "FIND/A,REPLACE/A";

ARGS = {{
    STRPTR  find;
    STRPTR  replace;
    //ULONG  *bufsize;
}};

USERDATA = {{
    UBYTE *buffer;
    ULONG  blen;
}};

BUFFERS = { buffer; };

INCLUDES = {{
#include <strings.h>
}};

INIT = {{
    ULONG blen = 4000;
    //if (argv->bufsize && *argv->bufsize)
	blen = *argv->bufsize;
    //if (!(userdata->buffer = AllocVec(blen + 1, MEMF_CLEAR))) {
    //	  SetIoErr(ERROR_NO_FREE_STORE);
    //	  return 20;
    //} /* if */
    userdata->blen = blen;
}};

BODY = {{
    //static ULONG freadln (BPTR fh, STRPTR buf, ULONG size, struct _gvars *gvars);
    int    current, recent;
    int    ilen, flen, rlen, blen;

    flen   = strlen (argv->find);
    rlen   = strlen (argv->replace);
    blen   = userdata->blen;


    /* ---- we decided to use an own readfunc in order */
    /*	    to be able to handle binary files	       */

    while (ilen = freadln(infile, userdata->buffer, blen, gvars)) {
	if (BREAKCHECK())
	    break;

	current = 0;
	recent	= 0;
//if (0) /* ****************************************************************** */
	while (current < ilen) {
	    if (userdata->buffer[current] == argv->find[0]) {
		if (strncmp(userdata->buffer+current, argv->find, flen) == 0) {
		    FWrite(outfile, userdata->buffer + recent, 1, current - recent);
		    FWrite(outfile, argv->replace, 1, rlen);
		    recent = current += rlen;
		    continue;
		} /* if */
	    } /* if */
	    ++current;
	} /* while */

	FWrite(outfile, userdata->buffer + recent, 1, ilen - recent);
    } /* while */
}};

EXIT = {{
    //FreeVec (userdata->buffer);
}};

APPEND = {{

static __inline ULONG freadln (BPTR fh, STRPTR buf, ULONG size, struct _gvars *gvars)
{
    ULONG free = size;
    int c = 0;
    while (free && (c = FGetC(fh)) != EOF) {
	--free;
	*(buf++) = c;
	if (c == '\n')
	    break;
    }
    if (free) *buf = 0;
    return size-free;
} /* freadln */
}};
#endif
