/*
    replace: a mini-app to replace a token in a string with another token.
    Copyright (C) 2006-2008, Aaron Griffin <aaronmgriffin@gmail.com>
                             Thomas Baechler <thomas@archlinux.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.
*/

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

void usage(char *progname) {
    fprintf(stderr, "usage: %s [-q] [-s <stop at>] <string> <to replace> [<with what>]\n", progname);
}

int main(int argc, char **argv)
{
    int opt, q = 0;
    char stop_at = '\0';
    char *with_what = " ";
    char *str = NULL;

    while((opt = getopt(argc, argv, "qs:")) != -1) {
        switch(opt) {
            case 'q':
                /* Use -q to quote output */
                q = 1;
                break;
            case 's':
                /* Use -s X to only replace before the first occurence of X */
                stop_at = optarg[0];
                break;
            default: /* '?' */
                usage(argv[0]);
                return 1;
        }
    }

    if(argc == optind+3)
        with_what = argv[optind+2];
    else if(argc < optind+2 || argc > optind+3) {
        usage(argv[0]);
        return 1;
    }

    str = argv[optind];
    if(q)
        printf("\"");
    while(*str) {
        if(*str == stop_at)
            break;
        else if(!strncmp(str, argv[optind+1], strlen(argv[optind+1]))) {
            if(q)
                printf("\"%s\"", with_what);
            else
                printf("%s", with_what);
            str += strlen(argv[optind+1]);
        }
        else
            printf("%c", *(str++));
    }
    if(q)
        printf("\"");
    printf("%s\n", str);

    return 0;
}
