/* compacts variables (written mainly for PATH)                        */
/*                                                                     */
/* usage:                                                              */
/*    pathize [-s separator] [-r remove] list                          */
/*                                                                     */
/* csh examples:                                                       */
/*    setenv PATH `pathize -r /usr/local/bin -r /sbin $PATH`           */
/*    set path = `pathize -s ' ' "$path"`                              */
/*                                                                     */
/* requires structural get_opts.  to compile:                          */
/*    gcc -o pwcr pwcr.c -I<get_opts_dir> -L<get_opts_dir> -lget_opts  */
/*                                                                     */
/* ari edelkind (??/??/1998)                                           */
/* full rewrite  06/20/2001                                            */
/* last modified 06/20/2001                                            */


#include <stdio.h>
#include <string.h>
#include "get_opts.h"

unsigned int count_chars();
void send_list();
void usage();

/* set up options */
add_opt (opt_s, "s", "separator", OPT_CHAR,   (opt_char_t)':', 0);
add_opt (opt_r, "r", "remove",    OPT_STRINGLIST, (opt_stringlist_t)0, 0);
put_opts(options, &opt_s, &opt_r);

int main(int argc, char **argv) {
	int argn;
	char **args;

	argn = get_opts_errormatic (&args, argv+1, argc-1, options);

	if (argn != 1) usage();

	/* item:item == 2 items, 1 char */
	send_list (*args, count_chars (*args, opt_s.v_opt.opt_char)+1);

	_exit (0);
}

void send_list (s, items)
	char *s;
	unsigned int items;
{
	char *list[items + 1]; /* add 0 */
	char *sp = s;
	char c = opt_s.v_opt.opt_char;
	char cp[2];
	unsigned int i = 0, out = 0;

	list[0] = sp;
	for (;;) {
		if (!*sp) break; if (*sp++ == c) {*(sp-1) = 0; list[++i] = sp;}
		if (!*sp) break; if (*sp++ == c) {*(sp-1) = 0; list[++i] = sp;}
		if (!*sp) break; if (*sp++ == c) {*(sp-1) = 0; list[++i] = sp;}
	}
	list[++i] = 0;

	i = 0;
	cp[0] = c; cp[1] = 0;
	for (;;) {
		unsigned int j;
		if (!list[i]) break;

		if (i) { /* unnecessary for i == 0 */
			for (j = i; j--;) {
				if (!strcmp(list[i], list[j])) goto END;
			}
		}

#define opt_r_sl opt_r.v_opt.opt_stringlist

		if (opt_r_sl) {
			for (j = 0; j < opt_r_sl->n; j++)
				if (!strcmp(list[i], opt_r_sl->sl[j]))
						goto END;
		}

		printf ("%s%s", out++ ? cp : "", list[i]);

END:
		i++;
	}

	printf ("\n");
	fflush(stdout);
	_exit(0);
}

	

unsigned int count_chars (s, c)
	register char *s;
	register char c;
{
	register unsigned int count = 0;

	for (;;) {
		if (!*s) break; if (*s++ == c) ++count;
		if (!*s) break; if (*s++ == c) ++count;
		if (!*s) break; if (*s++ == c) ++count;
	}

	return count;
}

void usage() {
	fprintf (stderr, "usage: pathize [-s separator] [-r remove] <list>\n");
	_exit (1);
}
