/**
 * vim: tabstop=2:shiftwidth=2:softtabstop=2:expandtab
 *
 * str_replace.c implements a str_replace PHP like function
 * Copyright (C) 2009  chantra <chantra__A__debuntu__D__org>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * gcc -o str_replace str_replace.c
 */
#include <string.h>
#include <stdio.h>
#include <stdlib.h>


void usage(char *p){
	fprintf(stderr, "USAGE: %s string tok replacement\n", p );
}

/*
 * Create a new string with [substr] being replaced by [replacement] in [string]
 * Returns the new string, or NULL if out of memory.
 * The caller is responsible for freeing this new string.
 */
char *
str_replace( const char *string, const char *substr, const char *replacement ){
  char *tok = NULL;
  char *newstr = NULL;

  tok = strstr( string, substr );
  if( tok == NULL ) return strdup( string );
  newstr = malloc( strlen( string ) - strlen( substr ) + strlen( replacement ) + 1 );
  if( newstr == NULL ) return NULL;
  memcpy( newstr, string, tok - string );
  memcpy( newstr + (tok - string), replacement, strlen( replacement ) );
  memcpy( newstr + (tok - string) + strlen( replacement ), tok + strlen( substr ), strlen( string ) - strlen( substr ) - ( tok - string ) );
  memset( newstr + strlen( string ) - strlen( substr ) + strlen( replacement ), 0, 1 );
  return newstr;
}

int main( int argc, char **argv ){

	char *ns = NULL;
	if( argc != 4 ) {
		usage(argv[0]);
		return 1;
	}
	ns = str_replace( argv[1], argv[2], argv[3] );
	fprintf( stdout, "Old string: %s\nTok: %s\nReplacement: %s\nNew string: %s\n", argv[1], argv[2], argv[3], ns );
	free(ns);
	return 0;
}

