/*  PROGRAM TO SUBSTITUTE SUFFIXES/PREFIXES
ssub [-pb] name s1 [s2]      replaces suffix s1 by suffix s2
     -S strip any leading path in output (i.e. basename behavior)
     -p act on prefix rather than suffix
     if s2 is unspecified, the suffix/prefix is simply deleted
     if no match is found, simply echo the input */

#include "addon.h"
typedef enum bool { FALSE, TRUE } bool;
extern void set(bool);

#include <string.h>
#include <stdio.h>
void b_ssub(char* av[]) {
    char *name, *s1, *s2, *out, *tmp, ctmp;
    int ac=0, beg=0, strip=0, subst, both, l1, lname, flags;

    while (av[ac]!=0) ac++;

    if (ac<3 || ac>5) {
        printf("usage: ssub [-pS] name s1 s2\n");
        set(FALSE);
        return;
    }
    if (ac==4 || ac==5) {                               /* parse command line */
        both =  strcmp(av[1],"-Sp")==0 || strcmp(av[1],"-pS")==0;
        beg =   both || strcmp(av[1],"-p")==0;
        strip = both || strcmp(av[1],"-S")==0;
        if (beg||strip) subst=(ac==5); else subst=(ac==4);
    }

    flags= (beg||strip) ? 1 : 0;
    name=av[1+flags];
    s1 = av[2+flags];
    s2 = av[3+flags];
    l1 = strlen(s1);
    if (strip)                               /* strip leading path if desired */
        if ((tmp = rindex(name,'/')) != NULL)
            name = tmp + 1;
    lname = strlen(name);

    if (beg) {                                  /* remove s1 if it's a prefix */
        ctmp = name[l1];
        name[l1] = '\0';
        if (strcmp(s1,name)==0)                    /* it's a prefix all right */
            out = name+l1;
        name[l1] = ctmp;
    } else {                                    /* remove s1 if it's a suffix */
        if (strcmp(s1,name+lname-l1)==0) {
            out = name;
            out[lname-l1] = '\0';
        }
    }
    if (out == NULL)                                        /* print original */
        printf("%s\n",name);
    else {                                               /* print replacement */
        if (subst&&beg) {
            if (s2==NULL) printf("%s",out); else printf("%s%s",s2,out);
            set(TRUE);
            return;
        }
        if (subst)
            if (s2==NULL) printf("%s",out); else printf("%s%s",out,s2);
        else
            printf("%s",out);
    }
    set(TRUE);
    return;
}
