/* tribval.c - return value of an attribute
 */

#include <ctype.h>
#include "mstring.h"


/* Return the value of the attribute sequence starting at index *"n" in
 * string "str", and update the value of *n to point to the first character
 * after the attribute sequence.
 */
long mtribval(char *str, int *n)
{
	int a, b, s;

	if ((!str) || (!n))
		return (MTR_INVALID);

	if (!miscntl(str[*n]))
		return (MTR_INVALID);

	(*n)++;
	a = str[*n];
	if ((a == 0) || (a == 10))
		return (MTR_INVALID);

	if (isdigit(a)) {
		s = a - '1';
		(*n)++;
		a = str[*n];
		if ((a == 0) || (a == 10))
			return (MTR_INVALID);
		(*n)++;
		b = str[*n];
		for (; s > 0; s--) {
			if ((str[*n] == 0) || (str[*n] == 10))
				return (MTR_INVALID);
			(*n)++;
		}
	} else {
		(*n)++;
		b = str[*n];
		if (a == 'C') {
			if ((b == 0) || (b == 10))
				return (MTR_INVALID);
			(*n)++;
		}
	}

	switch (a) {
	case 'a':
		return (MTR_ALL_OFF);
	case 'B':
		return (MTR_BOLD);
	case 'U':
		return (MTR_UNDERLINE);
	case 'S':
		return (MTR_STANDOUT);
	case 'R':
		return (MTR_REVERSE);
	case 'F':
		return (MTR_FLASH);
	case 'b':
		return (MTR_BOLD_OFF);
	case 'u':
		return (MTR_UNDERLINE_OFF);
	case 's':
		return (MTR_STANDOUT_OFF);
	case 'r':
		return (MTR_REVERSE_OFF);
	case 'f':
		return (MTR_FLASH_OFF);
	}

	if (a != 'C')
		return (MTR_INVALID);

	switch (b) {
	case 'A':
		return (MTR_FORE_COLOUR | MTR_COL_DEFAULT);
	case 'K':
		return (MTR_FORE_COLOUR | MTR_COL_BLACK);
	case 'R':
		return (MTR_FORE_COLOUR | MTR_COL_RED);
	case 'G':
		return (MTR_FORE_COLOUR | MTR_COL_GREEN);
	case 'Y':
		return (MTR_FORE_COLOUR | MTR_COL_YELLOW);
	case 'B':
		return (MTR_FORE_COLOUR | MTR_COL_BLUE);
	case 'M':
		return (MTR_FORE_COLOUR | MTR_COL_MAGENTA);
	case 'C':
		return (MTR_FORE_COLOUR | MTR_COL_CYAN);
	case 'W':
		return (MTR_FORE_COLOUR | MTR_COL_WHITE);
	case 'a':
		return (MTR_BACK_COLOUR | MTR_COL_DEFAULT);
	case 'k':
		return (MTR_BACK_COLOUR | MTR_COL_BLACK);
	case 'r':
		return (MTR_BACK_COLOUR | MTR_COL_RED);
	case 'g':
		return (MTR_BACK_COLOUR | MTR_COL_GREEN);
	case 'y':
		return (MTR_BACK_COLOUR | MTR_COL_YELLOW);
	case 'b':
		return (MTR_BACK_COLOUR | MTR_COL_BLUE);
	case 'm':
		return (MTR_BACK_COLOUR | MTR_COL_MAGENTA);
	case 'c':
		return (MTR_BACK_COLOUR | MTR_COL_CYAN);
	case 'w':
		return (MTR_BACK_COLOUR | MTR_COL_WHITE);
	}

	return (MTR_INVALID);
}

/* EOF */
