#include "rc.h"

/* shift $* n places (default 1) */
/* MAD added:
shift <by> <variable name>
note that shift n '*' is not equivalent to shift n because of the special treatment of $0
*/

static void
badnum ( char * num ) {
	fprint ( STDERR_FILENO, "%s is a bad number\n", num );
	set ( FALSE );
}

void
b_shift ( char ** av ) {
	int shift = (av[1] == NULL ? 1 : a2u(av[1]));
	List *s, *dollarzero = NULL;
	if (shift < 0) {
		badnum(av[1]);
		return;
	}
	if (av[1] != NULL && av[2] != NULL) {
		if (av[3] != NULL) {
			arg_count("shift");
			return;
		} else {
			s = varlookup(av[2]);
		}
	} else {
		s = varlookup("*")->n;
		dollarzero = varlookup("0");
	}
	while (s != NULL && shift != 0) {
		s = s->n;
		--shift;
	}
	if (s == NULL && shift != 0) {
		fprint(2, "cannot shift\n");
		set(FALSE);
	} else {
		if (av[1] != NULL && av[2] != NULL) {
			varassign(av[2], s, FALSE);
		} else {
			varassign("*", append(dollarzero, s), FALSE);
		}
		set(TRUE);
	}
}

