
#include <string.h>

#include "rc.h"

/* echo -n omits a newline. echo -- -n echos '-n' */

extern int stoi ( char ** );
extern int capescape ( char ** );

void
b_echo(char **av) {
	char *format = "%A\n", *s, *bslash;
	if (*++av != NULL) {
		if (streq (*av, "-n")) {
			format = "%A";
			av++;
		} else if (streq (*av, "--")) {
			av++;
		}
	}
	s = nprint (format, av);
	while ((bslash = strchr (s, '\\'))) {
		if (bslash > s) {
			format = nalloc (bslash - s + 1);
			strncpy (format, s, bslash - s);
			*(format + (bslash - s)) = '\0';
			fprint (1, "%s", format);
		}
		s = bslash + 2;
		if (bslash [1] == 'a') {
			fprint (1, "\a");
		} else if (bslash [1] == '\\') {
			fprint (1, "\\");
		} else if (bslash [1] == 'b') {
			fprint (1, "\b");
		} else if (bslash [1] == 'r') {
			fprint (1, "\r");
		} else if (bslash [1] == '\"') {
			fprint (1, "\"");
		} else if (bslash [1] == 'f') {
			fprint (1, "\f");
		} else if (bslash [1] == 't') {
			fprint (1, "\t");
		} else if (bslash [1] == 'n') {
			fprint (1, "\n");
		} else if (bslash [1] == '\'') {
			fprint (1, "'");
		} else if (bslash [1] == 'v') {
			fprint (1, "\v");
		} else if (bslash [1] == '%') {
			if (*s) {
				if (!capescape (&s)) {
					fprint (1, "\\%%%c", *s);
				}
				s ++;
			} else {
				fprint (1, "\\%%");
			}
		} else if (bslash [1] == 0 && bslash [2] != 'x' && !(bslash [2] >= '0' && bslash [2] <= '9')) {
			fprint (1, "%c", '\0');
			if (*s == '\\') s ++;
		} else {
			s --;
			format = s;
			fprint (1, "%c", stoi (&s));
			if (format == s) {
				fprint (1, "\\");
			} else if (*s == '\\') {
				s ++;
			}
		}
	}
	fprint (1, "%s", s);
	set (TRUE);
}


/* general purpose string to integer conversion, takes decimal d, octal 0d, hex 0xd, binary %d or base 2 to 36 b_d where b is the base in decimal and d is a string of digits in the base */
/* writes back address of next character */

extern long int strtol(const char *, char **, int);


extern int
stoi (char **s)
{
	int base = 10;

	if (**s == '0' && *(*s + 1) == 'x') {
		base = 16;
		*s += 2;
	} else if (**s == '0') {
		base = 8;
		(*s) ++;
	} else if (**s == '%') {
		base = 2;
		(*s) ++;
	} else {
		base = (int) strtol (*s, s, 10);
		if (**s == '_') {
			(*s) ++;
		} else {
			return base;
		}
	}

	return (int) strtol (*s, s, base);
}
