
/*  Replace v1.00  */
/*  To be used with Search  */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <exec/types.h>
#include <exec/memory.h>
#include <dos/dos.h>

/*  Prototypes for the functions, so we don't continually get warnings  */
#include <clib/exec_protos.h>
#include <clib/dos_protos.h>

/*  A definition for output if incorrect arguments are entered  */
#define BANNER	"Replace v1.00 by Paul Mclachlan.  PUBLIC DOMAIN.\nUsage:\n\tReplace <fromfile> <string> <with> <tofile>"

/*  Some global variables  */
BYTE tracking=0, pasttrack=1;
LONG length;
CPTR insert;
CPTR from, to;
BYTE buffer[256];

/*  Prototype for my routine  */
void FreeAll( BYTE code );

void main( int argc, char *argv[] )
	{
	/*  We need 4 arguments + 1 for the name of the replace command  */
	if( argc != 5 )
		{
		puts( BANNER );
		FreeAll( 1 );
		}
	
	/*  Open files  */
	if( !(from = Open( argv[1], MODE_OLDFILE ) ) )
		{
		printf( "Could not open %s.\n", argv[1] );
		FreeAll( 1 );
		}
	if( !(to = Open( argv[4], MODE_READWRITE ) ) )
		{
		printf( "Could not open %s.\n", argv[1] );
		FreeAll( 1 );
		}
	
	/*  Read in the insert file  */
	length = strlen( argv[3] );
	insert = argv[3];
	
	/*  Begin  */
	while( Read( from, &buffer[tracking], 1 ) == 1 )
		{
		if( buffer[tracking] != argv[2][tracking] )
			{
			/*  Tracking failed.  This character is different  */
			if( tracking != 0 )
				{
				tracking=0;
				pasttrack++;
				}
			}
		else
			{
			if( tracking == (strlen( argv[2] )-1) )
				{
				/*  Complete match  */
				/*  Insert other string  */
				if( Write( to, (APTR) insert, length ) != length )
					FreeAll( 1 );
				/*  Clear tracking and pasttrack  */
				tracking=0;
				pasttrack=-1;
				}
			else
				{
				/*  This character is the same, but not finished yet  */
				tracking++;
				pasttrack=tracking;
				}
			}
		if( tracking == 0 && pasttrack != -1 )
			{
			/*  OK to write these characters out  */
			/*  (more than one if the tracking just failed  */
			Write( to, buffer, pasttrack );
			pasttrack = 1;
			}
		else
			if( pasttrack == -1 )
				pasttrack = 1;
		}
	FreeAll( 0 );
	}

/*  My cleanup code  */
/*  I never liked "bail_out" or "clean_up"..  */
/*  Maybe something with my compulsive hate of "_"'s  */
void FreeAll( BYTE code )
	{
	if( from )
		Close( from );
	if( to )
		Close( to );
	exit( code );
	}
