/** 
 * @defgroup util util
 * misc utility functions
 * @{
 */

#include <string.h>
#include "include/util.h"

/************************** Module **************************/
void u_print_help(char *name)
{
    printf("Usage: %s [OPTION]\n\n"
           "-h\t--help\tThis help\n"
           "-v\t--verbose\tIncrease verbosity (repeat for greater effect)\n",
           name);
}




/*********************************************************************/
/*! replace first occurrences of "find" in "string" by "replace"  
 * @param string (char *) string to work on 
 * @param find (char *) string to find 
 * @param replace (char *) string to replace found string */
char *u_strReplace(const char *string, char *find, const char *replace)
{
    char *result = NULL;
    int destpos;
    int f_length, r_length, s_length, delta;
    char *found = NULL;

    if(string && find) {
        /* 
         * find string  
         */
        if((found = strstr(string, find))) {

            r_length = strlen(replace);
            f_length = strlen(find);
            s_length = strlen(string);

            /* 
             * handle different search <-> replace length  
             */
            delta = r_length - f_length;

            /* 
             * optimize for delta = 0  
             */
            if(delta == 0) {
                memcpy(found, replace, r_length);
                result = strdup(string);
            }

            /* 
             * different length of search <-> replace strings  
             */
            else {

                /* 
                 * alloc memory  
                 */
                if((result = malloc(s_length + delta + 1))) {
                    /* 
                     * copy first part  
                     */
                    destpos = found - string;
                    memcpy(result, string, destpos);
                    /* 
                     * replace token  
                     */
                    memcpy(result + destpos, replace, r_length);
                    destpos += r_length;
                    /* 
                     * copy rest  
                     */
                    memcpy(result + destpos, found + f_length,
                           s_length + delta + 1 - destpos);
                    /* 
                     * terminate new string  
                     */
                    result[s_length + delta] = 0;

                }
                else {
                    perror("strReplace():");
                    result = NULL;
                }
            }
        }
    }
        
    return result;
}      

/** 
 * @} 
 */
